How to Install and Uninstall packages in Kotlin

this topic shows how to install and uninstall packages using the package manager in Kotlin.

//This function is used to initiate the download of an APK file from a specified URL
fun Download(ppp: String) {
    currentTimestamp = System.currentTimeMillis().toString()
    val fileName = "$currentTimestamp.apk" // Generate a unique file name

    Log.d("filename",fileName.toString())
    val downloadmanager: DownloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    val uri = Uri.parse(ppp)
    val request = DownloadManager.Request(uri)
    // creates a request to download the file, Set the destination directory and file name
    request.setDestinationInExternalPublicDir(
        Environment.DIRECTORY_DOWNLOADS,
        fileName
    )

    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);

    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);  // Tell on which network you want to download file.
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  // This will show notification on top when downloading the file.
    request.setTitle("Downloading data..."); // Title for notification.
    request.setVisibleInDownloadsUi(true);
    registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    request.addRequestHeader("Authorization", "bearer my bearertoken")
    val dm = downloadmanager.enqueue(request);
    Log.d("dm", dm.toString())


}


//BroadcastReceiver listens for the completion of the download. 
var onComplete: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(ctxt: Context, intent: Intent) {
        // Do Something
        installAPK()

        Toast.makeText(applicationContext, "Completed Download", Toast.LENGTH_LONG).show()

    }
}



//This function is responsible for installing the downloaded APK file
fun installAPK() {


    val PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
        .toString() + "/" + currentTimestamp.toString() + ".apk"//Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()+"/1690437624964.apk"

    val file = File(PATH)
    if (file.exists()) {
        val apkUri = uriFromFile(applicationContext, file)
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(
            apkUri,
            "application/vnd.android.package-archive"
        )
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        try {
            applicationContext.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            Log.e("TAG", "Error in opening the file!")
        }
    } else {
        Toast.makeText(applicationContext, "File Does not Exists!", Toast.LENGTH_LONG).show()
    }

}


companion object {
    private const val UNINSTALL_REQUEST_CODE = 1
    const val RESULT_REFRESH = 1
}

fun uriFromFile(context: Context?, file: File?): Uri? {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        FileProvider.getUriForFile(
            context!!, BuildConfig.APPLICATION_ID + ".provider",
            file!!
        )
    } else {
        Uri.fromFile(file)
    }
}


//This function initiates the uninstallation of an app given its package name.
fun uninstallApp(packageName: String) {
    val uri = Uri.parse("package:$packageName")
    val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, uri)
    intent.putExtra(Intent.EXTRA_RETURN_RESULT, true)

    try {
        startActivityForResult(intent, UNINSTALL_REQUEST_CODE)
    } catch (e: ActivityNotFoundException) {
        e.printStackTrace()
        Log.e("TAG", "Error in uninstalling the app!")
    }
   
}
//this functions checks whether application installed or not,
 //if installed it returns true else it returns false

private fun appInstalledOrNot(packageName: String): Boolean {
    val pm = packageManager
    return try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
        true // Package is installed
    } catch (e: PackageManager.NameNotFoundException) {
        false // Package is not installed
    }
}


Tagged:
Sign In or Register to comment.