Android 静态广播接收器未接收自定义意图
我的广播接收器似乎没有收到它正在收听的意图 我正在启动一个必须一直运行的后台服务。无论何时服务被终止,它都会向我的广播接收器发送一个意图,然后重新启动服务 这是我的服务的Android 静态广播接收器未接收自定义意图,android,android-intent,service,broadcastreceiver,android-manifest,Android,Android Intent,Service,Broadcastreceiver,Android Manifest,我的广播接收器似乎没有收到它正在收听的意图 我正在启动一个必须一直运行的后台服务。无论何时服务被终止,它都会向我的广播接收器发送一个意图,然后重新启动服务 这是我的服务的ondestory: @Override public void onDestroy() { Log.i(TAG, "onDestroy"); sendBroadcast(new Intent("com.myapp.app.RESTART_SERVICE")); stoptimertask();
ondestory
:
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
sendBroadcast(new Intent("com.myapp.app.RESTART_SERVICE"));
stoptimertask();
super.onDestroy();
}
这是我的收音机:
public class RestarterBroadcastReceiver extends BroadcastReceiver {
public RestarterBroadcastReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Service stopped, restarting...");
context.startService(new Intent(context, ActivityRecognitionService.class));
}
}
Android清单的重要一点是:
<receiver
android:name=".RestarterBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.myapp.app.RESTART_SERVICE"/>
</intent-filter>
</receiver>
为什么我的广播接收器没有收到目的?您的问题可能是Android Oreo实际上禁止了隐式广播。解决此问题的最简单方法是使用显式广播而不是隐式广播 尝试将您的服务的
ondestory
代码更改为以下内容:
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
// Here you're using an explicit intent instead of an implicit one
sendBroadcast(new Intent(getApplicationContext(), RestarterBroadcastReceiver.class));
stoptimertask();
super.onDestroy();
}
<receiver
android:name=".RestarterBroadcastReceiver"
android:enabled="true"
android:exported="true">
</receiver>
由于您不再使用intent操作,您还可以将Android清单更改为以下内容:
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy");
// Here you're using an explicit intent instead of an implicit one
sendBroadcast(new Intent(getApplicationContext(), RestarterBroadcastReceiver.class));
stoptimertask();
super.onDestroy();
}
<receiver
android:name=".RestarterBroadcastReceiver"
android:enabled="true"
android:exported="true">
</receiver>
希望这有帮助 @kelalaka在哪里,在广播课上?内容应该是什么?关于活动。onDestroy可能永远不会被调用。但正如您所看到的,我正在记录“ServiceOnDestroy”,我看到了这一点。但我并不是说“服务停止,重新启动服务…”而是在启动服务时使用该标志,以使其在停止时自行重新启动。@daka已经这样做了,服务仍然被终止。这似乎适用于我的情况。《开发者指南》中也提到了这一点: