Apk Update Code Added

This commit is contained in:
Mariya
2024-02-27 12:42:30 +05:30
parent eb1c764551
commit bb6f4ee859
4 changed files with 55 additions and 61 deletions

View File

@@ -8,7 +8,7 @@ object Constants {
const val ABHA_APP_PACKAGE = "in.ndhm.phr" const val ABHA_APP_PACKAGE = "in.ndhm.phr"
const val MOLBIO_INTEGRATION = false const val MOLBIO_INTEGRATION = true
const val deviceProvisionEmail = "HPOS_provisioner@bigtec.co.in" const val deviceProvisionEmail = "HPOS_provisioner@bigtec.co.in"
const val deviceProvisionPassword = "f2ab0e7f9d69" const val deviceProvisionPassword = "f2ab0e7f9d69"
const val DEVICE_ID_API = "deviceIDAPI" const val DEVICE_ID_API = "deviceIDAPI"

View File

@@ -172,7 +172,7 @@ class NatsManager(datacollector: DashboardActivity) {
println("Message received (up to 100 times): $response") println("Message received (up to 100 times): $response")
} }
d?.subscribe("device.hpos.${deviceId}.checkupdate") { msg -> d?.subscribe("device.hpos.${deviceId}.checkUpdate") { msg ->
val response = String(msg.data, StandardCharsets.UTF_8) val response = String(msg.data, StandardCharsets.UTF_8)
datacollector.setResponse(response) datacollector.setResponse(response)
println("Message received (up to 100 times): $response") println("Message received (up to 100 times): $response")

View File

@@ -1,7 +1,5 @@
package com.example.hpostesting.presentation.dashboard package com.example.hpostesting.presentation.dashboard
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.SharedPreferences import android.content.SharedPreferences
@@ -23,6 +21,7 @@ import androidx.navigation.ui.setupWithNavController
import com.example.hpostesting.data.Result import com.example.hpostesting.data.Result
import com.example.hpostesting.data.constant.Constants import com.example.hpostesting.data.constant.Constants
import com.example.hpostesting.data.constant.LanguageManager import com.example.hpostesting.data.constant.LanguageManager
import com.example.hpostesting.data.model.updates.DeviceUpdateRequest
import com.example.hpostesting.presentation.NatsManager import com.example.hpostesting.presentation.NatsManager
import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel import com.example.hpostesting.presentation.hemocube.HemoCubeViewModel
import com.example.hpostesting.presentation.jig.JigActivity import com.example.hpostesting.presentation.jig.JigActivity
@@ -35,6 +34,8 @@ import `in`.sminnovations.hpostesting.R
import `in`.sminnovations.hpostesting.databinding.ActivityDashboardBinding import `in`.sminnovations.hpostesting.databinding.ActivityDashboardBinding
import okhttp3.ResponseBody import okhttp3.ResponseBody
import java.io.File import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
interface NatsMessageCallback { interface NatsMessageCallback {
fun onMessageReceived(topic: String, message: String) fun onMessageReceived(topic: String, message: String)
@@ -57,7 +58,7 @@ class DashboardActivity : AppCompatActivity(), IDataCollector {
private var downloadId: Long = 0 private var downloadId: Long = 0
// TODO: Remove hemocube viewmodel // TODO: Remove hemocube viewmodel
private val hemocubeViewModel: HemoCubeViewModel by viewModels() private val hemocubeViewModel: HemoCubeViewModel by viewModels()
private lateinit var sharedPreference: SharedPreferences
override fun attachBaseContext(newBase: Context?) { override fun attachBaseContext(newBase: Context?) {
val languageCode = LanguageManager.getSavedLanguage(newBase!!) val languageCode = LanguageManager.getSavedLanguage(newBase!!)
LanguageManager.setLocale(newBase, languageCode) LanguageManager.setLocale(newBase, languageCode)
@@ -91,14 +92,13 @@ class DashboardActivity : AppCompatActivity(), IDataCollector {
is Result.Success -> { is Result.Success -> {
// Handle success // Handle success
val apkUrl = result.data val apkUrl = result.data
// val apkUrl = "https://dl.dropboxusercontent.com/s/fi/1c3nn7t0co431hicl3hrt/app-debug.apk?rlkey=e4uf13ty1dpcked614vy1aaqp&dl=0" downloadApk(apkUrl)
initiateUpdate(apkUrl.toString()) Log.e("ApI", "APK URL: $apkUrl")
Log.d("ApI", "APK URL: $apkUrl") Toast.makeText(
// Toast.makeText( this,
// this, "${result.data}",
// "APK UPLOAD ${result.data}", Toast.LENGTH_SHORT
// Toast.LENGTH_SHORT ).show()
// ).show()
} }
is Result.Error -> { is Result.Error -> {
@@ -145,69 +145,54 @@ class DashboardActivity : AppCompatActivity(), IDataCollector {
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
} }
private fun initiateUpdate(responseBody: String) { private fun downloadApk(responseBody: ResponseBody) {
val apkUrl = responseBody val file = File(getExternalFilesDir(null), "update.apk")
if (!isValidHttpUrl(apkUrl)) { var inputStream: InputStream? = null
return var outputStream: FileOutputStream? = null
} try {
val fileReader = ByteArray(4096)
val fileSize = responseBody.contentLength()
var fileSizeDownloaded: Long = 0
val request = DownloadManager.Request(Uri.parse(apkUrl)) inputStream = responseBody.byteStream()
request.setTitle("App Update") outputStream = FileOutputStream(file)
request.setDescription("Downloading update...")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalFilesDir(this, "Updates", "update.apk")
val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager while (true) {
downloadId = downloadManager.enqueue(request) val read = inputStream.read(fileReader)
if (read == -1) {
// Register a BroadcastReceiver to receive the download complete event break
// val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE) }
// registerReceiver(downloadReceiver, filter) outputStream.write(fileReader, 0, read)
} fileSizeDownloaded += read.toLong()
private fun extractApkUrl(responseBody: ResponseBody): String { Log.d(TAG, "File download: $fileSizeDownloaded of $fileSize")
return responseBody.string()
}
private fun isValidHttpUrl(url: String): Boolean {
return url.startsWith("http://") || url.startsWith("https://")
}
private val downloadReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (id == downloadId) {
installApk()
} }
outputStream.flush()
installApk(file) // Call installApk directly with the file
} catch (e: Exception) {
Log.e(TAG, "Error saving APK: ${e.message}")
} finally {
inputStream?.close()
outputStream?.close()
} }
} }
private fun installApk() { private fun installApk(file: File) {
val file = File(getExternalFilesDir("Updates"), "update.apk")
file.setReadable(true, false) // Ensure the file is readable
val pInfo = baseContext.packageManager.getPackageInfo(baseContext.packageName, 0)
val uri: Uri = FileProvider.getUriForFile( val uri: Uri = FileProvider.getUriForFile(
this, this,
"${pInfo}.fileprovider", "${applicationContext.packageName}.provider", // Update this with your FileProvider authority
file file
) )
// Create an intent to install the APK val installIntent = Intent(Intent.ACTION_VIEW).apply {
val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE) data = uri
installIntent.data = uri flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
installIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_CLEAR_TOP
Intent.FLAG_ACTIVITY_NEW_TASK or }
Intent.FLAG_ACTIVITY_CLEAR_TOP
installIntent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
// Start the installation
startActivity(installIntent) startActivity(installIntent)
Log.d("InstallApk", "Install Intent URI: $uri")
Log.d("InstallApk", "Package Name: $packageName")
} }
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
// unregisterReceiver(downloadReceiver)
} }
override fun onResume() { override fun onResume() {
@@ -260,5 +245,14 @@ class DashboardActivity : AppCompatActivity(), IDataCollector {
responses = responses+response+"\n" responses = responses+response+"\n"
println(responses) println(responses)
if (response.contains("checkUpdate")) {
hemocubeViewModel.deviceUpdate(createDeviceUpdateRequestData())
}
}
private fun createDeviceUpdateRequestData(): DeviceUpdateRequest {
return DeviceUpdateRequest(
serial_no = sharedPreference.getString(Constants.DEVICE_ID, "")
)
} }
} }

View File

@@ -3,7 +3,7 @@ buildscript {
kotlin_version = '1.8.21' kotlin_version = '1.8.21'
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:8.1.1' classpath 'com.android.tools.build:gradle:8.2.2'
classpath 'com.google.gms:google-services:4.4.0' classpath 'com.google.gms:google-services:4.4.0'
classpath 'com.google.firebase:firebase-appdistribution-gradle:4.0.1' classpath 'com.google.firebase:firebase-appdistribution-gradle:4.0.1'
} }