Search code examples
androidroot

Android silently updating apk and then restart the app


Okay first of all I want to clear, I'm not trying to achieve anything fishy. We have our own enterprise app that only goes with our own hardware (we are not using Google play store). Also the phone is rooted. I have implemented our own Apk update mechanism. So far I have successfully silently installed apk using the below code

    try {
        val command = "pm install -r " + file.path
        val openAppCommand = "am start -a android.intent.action.MAIN -n" +
                BuildConfig.APPLICATION_ID + "/.MainActivity"
        val process = Runtime.getRuntime().exec(arrayOf("su", "-c", command, openAppCommand))

        val exitVal = process.waitFor()
        if (process.exitValue() == 0) {
            Log.e("updateAppSilently", "Apk installed")
        } else {
            Log.e("updateAppSilently", "Something went wrong while installing apk")
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

openAppCommand is getting ignore because after restart the current process is killed.

I have even tried

       <receiver android:name="com.updatesmanager.AppUpdateBroadcastReceiver"
            android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
            </intent-filter>
        </receiver>

and the class file

class AppUpdateBroadcastReceiver : BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d("AppUpdateBroadcastReceiver", "App got updated!")
        val intent = Intent(context, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

        context?.startActivity(intent)


       /* Log.d("AppUpdateBroadcastReceiver", "App got updated!")
        val command = "am start -a android.intent.action.MAIN -n" +
                BuildConfig.APPLICATION_ID + "/.MainActivity"
        val process = Runtime.getRuntime().exec(arrayOf("su", "-c", command))
        val exitVal =  process.waitFor()

        if(exitVal == 0){
            Log.e("AppUpdateBroadcastReceiver", "App launched")
        }*/
    }

}

I have even tried setting alarm but it will not work because the app is updated/reinstall so the alarms gets cleared.

Any kind of help is highly appreciated.


Solution

  • Okay, that's silly though but I was not updating the versionCode of the update apk (Although I strongly believe that the broadcast receiver should trigger in case when pm install -r command is ran regardless of the versionCode, because the package is replaced). When I increased the versionCode from the current apk. The AppUpdateBroadcastReceiver did got triggered.