Android的 - 如何使用本地广播接收器? [英] Android - How to use a local broadcast receiver?

查看:482
本文介绍了Android的 - 如何使用本地广播接收器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用本地广播接收器。

I'm trying to use a local broadcast receiver.

为了这样做,我已经做下一个步骤 -

In order to do so I"ve done the next steps -

1)在活动,其中像再去读事情发生,我创建了一个类 -

1) At an Activity, where Iwould like something to happen, I've created a class -

private class NewGroupReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("The group ", "GOT IN THE RECIVING");
        Toast.makeText(this, "Working",Toast.LENGTH_SHORT).show();  
    }

}

2)在同一个活动,我用接下来的code,以创建一个接收器 -

2) At the same activity I've used the next code in order to create a receiver -

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    NewGroupReceiver receiver = new NewGroupReceiver();

    //the intent filter will be action = "com.example.demo_service.action.SERVICE_FINISHED"
    IntentFilter filter= new IntentFilter("com.example.apps.action.NEW_GROUP");

    // register the receiver:
    registerReceiver(receiver, filter);
}

3)在一个服务类,我用了接下来的code知道什么时候出事了 -

3) At the a service class I've used the next code to know when something has happened-

Intent resultsIntent=new Intent("com.example.apps.action.NEW_GROUP");

LocalBroadcastManager localBroadcastManager =LocalBroadcastManager.getInstance(this);

localBroadcastManager.sendBroadcast(resultsIntent);

现在的问题是,当我想知道的东西有发生 - 我看到了它的进入,我已经用在步骤3中的code,但它doesen't似乎进入了BroadcastReceiver - 步骤1 code

Now the problem is that when the thing I WOuld like to know has happen - I see the it's get into the code that I've used at step 3, but it doesen't seem to get into the BroadcastReceiver - the step 1 code.

任何想法,我究竟做错了什么? 感谢任何形式的帮助。

Any idea what am I doing wrong here? Thanks for any kind of help.

推荐答案

您使用的是LocalBroadcastManager发送请求,但你注册了glogal意向接收器。您应该使用LocalBroadcastManager登记接收或发送广播上 应用程序上下文:

You are using the LocalBroadcastManager to send the request, but you register the receiver on the "glogal" Intent. You should either use LocalBroadcastManager to register the receiver or send the broadcast on the application context:

第2步

LocalBroadcastManager.getInstance(this).registerReceiver (receiver, filter);

这篇关于Android的 - 如何使用本地广播接收器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆