3

我的应用程序运行一项服务,当设备重新启动或应用程序重新安装(更新)时终止。我添加了两个广播接收器来捕获这些事件 - BOOT_COMPLETED和ACTION_MY_PACKAGE_REPLACED。Android:广播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

回答

12

你可能想通了这一点了,但在清单的动作名称是错误的,而不是:

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 
+2

无法在Android 7 Nougat上使用adb命令模拟此意图,似乎现在它在敏感意图列表中:“java.lang.SecurityException:Permission Denial:not allowed to send broa dcast android.intent.action.MY_PACKAGE_REPLACED“。尽管在Kit-Kat 4.4上完美运行,但即使没有adb命令,每当我在Android Studio中启动应用程序时,它都会在接收器中调用我的断点 – 2017-04-17 21:41:21

1

ACTION EXPLAIN IMAGE

要考虑到:

  1. 您的应用程序的新版本
  2. 您应该运行ADB安装-r新版本的APK,如果你只是在Android Studio中它赢得运行 ” t收到此广播