Android 未调用onReceive方法
我尝试使用Android 未调用onReceive方法,android,intentservice,android-intentservice,Android,Intentservice,Android Intentservice,我尝试使用IntentService将广播从服务发送到活动,为此我使用了以下代码: public class NotifyService extends IntentService { public NotifyService() { super("NotifyService"); } // will be called asynchronously by Android @Override protected void onHandl
IntentService
将广播从服务发送到活动,为此我使用了以下代码:
public class NotifyService extends IntentService {
public NotifyService() {
super("NotifyService");
}
// will be called asynchronously by Android
@Override
protected void onHandleIntent(Intent intent) {
Log.d("onHandleIntent", "start service");
publishResults();
}
private void publishResults() {
result = Activity.RESULT_OK;
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
然后我在活动类中定义接收者,如:
public BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "receiver");
Bundle bundle = intent.getExtras();
if (bundle != null) {
int resultCode = bundle.getInt(NotifyService.RESULT);
if (resultCode == RESULT_OK) {
Toast.makeText(Home.this, "after service work.", Toast.LENGTH_LONG)
.show();
}
}
stopService(new Intent(Home.this,NotifyService.class));
}
};
我在onResume
中使用了registerReceiver
,在onPause
方法中使用了unregisterReceiver
registerReceiver(receiver, new IntentFilter(NotifyService.NOTIFICATION));
但是,onReceive
方法没有被调用
我使用了第7节
我错过了什么
编辑
我有别的解决办法吗?我已尝试从服务通知活动以更新数据。我不确定您的原始代码为什么不起作用。但是,如果您想要应用程序本地广播,您可能希望使用一个本地应用程序,而不是常规的跨应用程序广播 在您的服务中使用此选项:
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
在你的活动中:
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(NotifyService.NOTIFICATION));
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
如果这改变了什么,请告诉我。同样,我不明白为什么您的原始代码不起作用,所以这更像是猜测。您确定您的服务已经启动了吗<代码>Log.d(“onHandleIntent”,“启动服务”)代码>此日志已打印?是@artemzinnatullin当您的接收器未注册时,您可能正在发送广播意图?因为您的代码看起来正常:)@ArtemZinnatullin我在
onResume
方法中注册了接收器,并且我在活动运行时发送广播,所以我认为没有理由不注册接收器。感谢您的回复,您不必在已为您处理的IntentService
上明确使用stopService
。虽然我怀疑这是你问题的根源…谢谢,伙计,我的代码有问题,我开始另一个活动,所以调用了此活动的onPause()
,然后调用了unregisterReceiver
,所以onReceive
没有被调用,我修复了我的问题,但你的代码也起了作用,谢谢回复。@user2910110这解释了很多。当然,如果您在暂停时取消注册,当您的活动不再在前台时,您将不会收到广播!