Android:广播ACTION_MY_PACKAGE_REPLACED从未收到过

问题描述 投票:5回答:3

我的应用程序运行的服务在设备重新启动或重新安装(更新)应用程序时终止。我添加了两个广播接收器来捕获这些事件 - BOOT_COMPLETED和ACTION_MY_PACKAGE_REPLACED。

ACTION_MY_PACKAGE_REPLACED接收器似乎不起作用。这就是我所拥有的:

AndroidManifest.xml中:

    <receiver android:name=".RebootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
    <receiver android:name=".ReInstallReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_MY_PACKAGE_REPLACED"/>
        </intent-filter>
    </receiver>

RebootReceiver:

public class RebootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Logg.d("Reboot completed. Restarting service");
        context.startService(new Intent(context, MyService.class));
    }
}

ReInstallReceiver:

public class ReInstallReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Logg.d("App Upgraded or Reinstalled. Restarting service");
        context.startService(new Intent(context, MyService.class));
    }
}

运行minSdk = 16;在运行KitKat的Galaxy S3上进行测试。通过检查我的服务是否在“设置/应用程序”中运行来测试成功,它在重新启动时执行,但不重新安装。

我已经考虑了以下注释,其中说在Android Studio 1.0+中,清单合并意味着我无法将两个接收器合并为一个类。见ACTION_MY_PACKAGE_REPLACED not receivedAndroid manifest merger fails for receivers with same name but different content

android android-studio broadcastreceiver android-broadcast
3个回答
16
投票

您可能已经想到了这一点,但是清单中的操作名称是错误的,而不是:

android.intent.action.ACTION_MY_PACKAGE_REPLACED

它应该是

android.intent.action.MY_PACKAGE_REPLACED

您还可以使用adb shell手动触发接收器以进行测试:

adb shell am broadcast -a android.intent.action.MY_PACKAGE_REPLACED -n com.example.myapp/.ReInstallReceiver

4
投票

考虑到:

  1. 新版应用程序
  2. 您应该运行adb install -r您的新版本apk,如果您只是在Android Studio上运行它将不会收到此广播

4
投票

我想用新答案更新这个帖子,因为我没有找到提供Android 7.0+更新解决方案的帖子,这个Intent现在受到保护。

转到Build -> Build APK,并记下.apk存储的位置。

然后,在终端运行:

adb install -r debugapp.apk

这将触发MY_PACKAGE_REPLACED意图,因为较新的Android SDK仅允许系统广播它。

© www.soinside.com 2019 - 2024. All rights reserved.