【问题标题】:onReceive method not getting calledonReceive 方法没有被调用
【发布时间】:2014-04-27 06:59:44
【问题描述】:

我尝试使用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);

    }
}

然后我在 Activity 类中定义我的接收器,例如:

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 方法没有被调用,

我用过This Site的第7节

我错过了什么?

编辑

我有其他解决方案吗?我已尝试通过服务通知活动以更新数据。

【问题讨论】:

  • 你确定你的服务已经启动了吗? Log.d("onHandleIntent", "start service");此日志已打印?
  • 是的@ArtemZinnatullin
  • 当您的接收器未注册时,您是否正在发送广播意图?因为你的代码看起来很正常:)
  • @ArtemZinnatullin 我在onResume 方法中注册了接收器,并且我在活动运行时发送广播,所以我认为接收器没有注册是没有原因的。感谢回复
  • 您不必在IntentService 上显式使用stopService,这已经为您处理好了。虽然我怀疑这是你问题的根源......

标签: android intentservice android-intentservice


【解决方案1】:

我不确定为什么您的原始代码不起作用。但是,如果您想要应用程序本地广播,您可能需要使用 LocalBroadcastManager 而不是常规的跨应用程序广播。

在您的服务中使用它:

LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

这些在你的活动中:

LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
        new IntentFilter(NotifyService.NOTIFICATION));

LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);

如果这有什么改变,请告诉我。同样,我不明白为什么您的原始代码不起作用,所以这更像是一个猜测。

【讨论】:

  • 谢谢,我的代码有问题,我开始另一个活动,所以这个活动的onPause() 被调用,然后unregisterReceiver 被调用,所以onReceive 没有被调用,我修复了我的问题,但您的代码也可以,谢谢您的回复。
  • @user2910110 这解释了很多。当然,如果你在onPause取消注册,当你的activity不再在前台时你就不会收到广播了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
相关资源
最近更新 更多