[英]onReceive method not getting called
我嘗試使用IntentService
將廣播從服務發送到Activity,因為我使用了以下代碼:
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);
}
}
然后在Activity類中定義我的Receiver:
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而不是常規的跨應用程序廣播。
在您的服務中使用此功能:
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
這些在您的活動中:
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(NotifyService.NOTIFICATION));
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
讓我知道這是否有任何變化。 再說一次,我不明白為什么您的原始代碼不起作用,所以這更多的是猜測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.