我相信这个问题重复了这个 Auto-restart app after market update
每当我在市场中发布应用的新版本时,如果用户启用了“自动更新”选项,应用就会自动更新。
该应用程序包含一项持续运行的服务。但是,当自动更新发生时,旧的正在运行的应用程序将被终止,但新的应用程序不会启动。由于更新对用户来说基本上是透明的,因此应用程序的服务应该在更新后自动重新启动,这样服务几乎不会中断。
用市场上的真实更新来测试这个有点困难,所以我使用以下两个 adb 命令来模拟这个更新过程。安装第一个版本:
adb install oldversion.apk//(版本号为 1 ) 自动更新:
adb install -r newversion.apk//(版本号为2)
就我而言,我有两个 Activity ,第一个是 MainActivity,第二个是 MainActivity。如果用户正在使用第二个Activity并且应用程序自动更新(对我来说,我使用adb命令安装新版本),如何在应用程序成功更新新版本后触发运行MainAcitivty?
最佳答案
我也认为这是重复的问题。您是否尝试过在 Intent 过滤器中使用 MY_PACKAGE_REPLACED
来注册广播? (设备重新启动时也会触发,可能有用)
list :
<receiver
android:name=".OnUpdateReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
代码:
public class OnUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null ||
(!Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction()) &&
!Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())))
return;
// your code, start your Service again or
// Activity if it is REALLY desired behavior
}
}
您可以使用此命令测试此代码,无需“真正”更新
adb shell am broadcast -a android.intent.action.MY_PACKAGE_REPLACED -n com.yourapp/.OnUpdateReceiver
还有support for in-app updates直接来自官方 Google Play Core API,也许这会用最少的代码解决您的问题
关于java - Android 更新新版本后重新启动应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59027975/