如何以编程方式静默更新apk并重新启动应用程序?

Boo*_*Tan 13 android

我在StackOverFlow和其他网站上尝试了很多方法,但它并没有真正起作用.

我的问题是我有这个应用程序,我需要更新,更新后,它应该自动重新启动相同的应用程序(更新).

这是我的代码:

private synchronized void runRootUpdate() {    
    // Install Updated APK
    String command = "pm install -r " + downloadPath + apkFile;
    Process proc = Runtime.getRuntime().exec(new String[] {"su", "-c", command});
    int test = proc.waitFor(); // Error is here.

    if (proc.exitValue() == 0) {
        // Successfully installed updated app
        doRestart()
    } else {
        // Fail
        throw new Exception("Root installation failed");
    }
}

private void doRestart() {
    Intent mStartActivity = new Intent(context, MainActivity.class);
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);
}
Run Code Online (Sandbox Code Playgroud)

看看我的"错误就在这里".我的旧应用程序将安装一个新的更新的应用程序并自行终止,因此没有proc.waitFor()并最终回到主屏幕但是正在安装新的更新的应用程序.但是,我需要它自己回来.有什么办法可以吗?

Nic*_*oso 7

而不是设置警报,而是专门为此目的注册了一个Manifest注册的BroadcastReceiver.它可以听android.intent.action.PACKAGE_REPLACED(注意:这个常量中缺少单词动作)或者android.intent.action.MY_PACKAGE_REPLACED

<receiver android:name="...">
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_REPLACED"></action>
        <data android:scheme="package" android:path="com.your.package" /> 
    </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)

重新安装后,您的接收器将收到此消息,您将能够启动活动


bwt*_*bwt 0

更新应用程序涉及终止其所有进程。您应该在启动 pm 命令之前设置警报(延迟超过 100 毫秒)