作者:mobiledu2502879733 | 来源:互联网 | 2023-05-22 19:36
我的应用程序运行的服务在设备重新启动或重新安装(更新)应用程序时终止.我添加了两个广播接收器来捕获这些事件 - BOOT_COMPLETED和ACTION_MY_PACKAGE_REPLACED.
ACTION_MY_PACKAGE_REPLACED接收器似乎不起作用.这就是我所拥有的:
AndroidManifest.xml中:
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未收到,并且对于具有相同名称但内容不同的接收者,Android清单合并失败
1> G. Lombard..:
您可能已经想到了这一点,但是清单中的操作名称是错误的,而不是:
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
无法在Android 7 Nougat上使用adb命令模拟此意图,现在它似乎在敏感意图列表中:"java.lang.SecurityException:Permission Denial:不允许发送广播android.intent.action.MY_PACKAGE_REPLACED".在Kit-Kat 4.4上完美运行,即使没有adb命令,每次我在Android Studio中启动应用程序时它都会在接收器中调用我的断点
2> Bryan W..:
我想用一个新的答案来更新此线程,因为我发现没有帖子提供了适用于Android 7.0+的更新解决方案,而该解决方案Intent
现已受到保护。
转到Build -> Build APK
,然后注意.apk的存储位置。
然后,在终端中运行:
adb install -r debugapp.apk
这将触发MY_PACKAGE_REPLACED
意图,因为较新的Android SDK仅允许系统对其进行广播。