首页 > 解决方案 > Android静默更新apk然后重启应用

问题描述

好的,首先我想澄清一下,我并不想做任何可疑的事情。我们有自己的企业应用程序,仅与我们自己的硬件配套使用(我们没有使用 Google Play 商店)。手机也root了。我已经实现了我们自己的 Apk 更新机制。到目前为止,我已经使用下面的代码成功地安装了 apk

    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 被忽略,因为重启后当前进程被杀死。

我什至尝试过

       <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>

和类文件

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")
        }*/
    }

}

我什至尝试设置警报,但它不起作用,因为应用程序已更新/重新安装,因此警报被清除。

任何形式的帮助都将受到高度赞赏。

标签: androidroot

解决方案


好的,虽然这很愚蠢,但我没有更新更新 apk 的 versionCode(尽管我坚信广播接收器应该在pm install -r运行命令时触发,而不考虑 versionCode,因为包已被替换)。当我从当前 apk 增加 versionCode 时。AppUpdateBroadcastReceiver 确实被触发了。


推荐阅读