0

我尝试使用 将广播从服务发送到活动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));
    }
};

我用过registerReceiverinonResumeunregisterReceiverinonPause方法

registerReceiver(receiver, new IntentFilter(NotifyService.NOTIFICATION));

但是该onReceive方法没有被调用,

我已使用本网站的第 7 部分

我错过了什么?

编辑

我有任何替代解决方案吗?我尝试通知服务活动以更新数据。

4

1 回答 1

1

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

在您的服务中使用它:

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

这些在您的活动中:

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

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

让我知道这是否会改变任何事情。同样,我不明白为什么您的原始代码不起作用,所以这更像是一个猜测。

于 2014-04-27T09:04:48.330 回答