Android:无法通过Broadcastreceiver从Service to Activity接收数据

时间:2013-09-19 11:24:37

标签: android service broadcastreceiver

我有一项活动和服务。我通过AlaramManager在一个时间间隔内在后台运行我的服务。我想要的是定期从服务内部活动接收数据。为此,我使用broadcastreceiver,但它没有显示任何数据。

在我的服务中,我正在使用此方法发送数据:

        private final void sendServiceActiveBroadcast(final boolean pActivate) {
        final Intent _intent = new Intent();
        _intent.setAction(BROADCAST_ACTION);
        _intent.addCategory("com.monday.worker_android.android.CATEGORY");
        _intent.putExtra("isactive", pActivate);

        NewService.this.sendBroadcast(_intent);
    }

并在AsyncTask类中使用它,如:

      @Override
        protected void onPostExecute(String result) {
        Log.d("Post Execute", "Executed");
        super.onPostExecute(result);
        float[] arr = new float[30];
        if (round(distance(LATITUDE, LONGITUDE, lati, longi)) < 200) {
        Log.d("OnPostExecute", "In");
        sendServiceActiveBroadcast(true);
       }
  }

并试着在我的活动中收到这个:

    private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean value = intent.getBooleanExtra("isactive", false);
        if (value == true) {
            Toast.makeText(getApplicationContext(), "received",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), " not received",
                    Toast.LENGTH_SHORT).show();
        }

    }
};

我在我的onResume()中取消它并在我的onPause()中取消它,如:

@Override
protected void onResume() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(NewService.BROADCAST_ACTION);
    registerReceiver(receiver, filter);     
    super.onResume();
    }

    @Override
    protected void onPause() {
    unregisterReceiver(receiver);
    super.onPause();
}

我只是查看一些教程并对其进行编码。我的应用程序在服务上工作正常,并且它完美地解决了onPostExecute()。但它没有显示任何广播数据。

任何人都可以建议我如何定期收到服务中的数据,以及为什么我这里没有收到数据以及我的错误。

谢谢

1 个答案:

答案 0 :(得分:1)

addCategory

是代码中的问题。因为,在您的活动中,您未设置category属性,因此无法找到引用。此外,如果没有类别,您可以使用action属性将其发送到位于不同位置的多个接收器。

相关问题