【问题标题】:Restart App after updating a new version in android在android中更新新版本后重新启动应用程序
【发布时间】:2019-11-25 17:31:13
【问题描述】:

我相信这个问题重复了这个 Auto-restart app after market update

每当我在 Market 中发布我的应用的新版本时,如果用户启用了“自动更新”选项,应用就会自动更新。

该应用程序包含一个持续运行的服务。但是当自动更新发生时,旧的正在运行的应用程序被杀死,但新的应用程序没有启动。由于更新对用户来说大多是透明的,因此应用的服务应该在更新后自动重新启动,这样服务几乎不会中断。

用市场上的真实更新来测试这个有点困难,所以我使用以下两个 adb 命令来模拟这个更新过程。安装第一版:

adb install oldversion.apk // (版本号为 1 ) 自动更新:

adb install -r newversion.apk //(版本号为2)

就我而言,我有两个活动,第一个是 MainActivity,第二个是活动。如果用户正在使用 secondActivity 并且应用程序自动更新(对我来说,我正在使用 adb 命令安装新版本),如何在应用程序成功更新新版本后触发运行 MainAcitivty?

【问题讨论】:

标签: java android mobile


【解决方案1】:

我也相信这是重复的问题。您是否尝试过在意图过滤器中使用MY_PACKAGE_REPLACED 进行注册广播? (设备重启时也会触发,可能有用)

清单:

<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

还有直接来自官方 Google Play Core API 的 support for in-app updates,也许这可以用最少的代码解决您的问题

【讨论】:

  • 感谢您的回答,是的,我确实尝试过,但作为 API 28 中的 google 文档,不再支持 ACTION_MY_PACKAGE_REPLACED。注意:其他与包相关的广播(例如 ACTION_PACKAGE_REPLACED)也不受新限制的约束。这些广播很常见,因此豁免它们可能会对性能产生影响。 developer.android.com/guide/components/…
  • 您能否为此提供一些链接(此操作已弃用/不再起作用)?根据DOCIntent - MY_PACKAGE_REPLACED 操作仍在使用中,根本没有被弃用,就像列表中的一些...
猜你喜欢
  • 2011-07-14
  • 2012-05-30
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多