Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

broadcastreceiver - Android - How to use a local broadcast receiver?

I'm trying to use a local broadcast receiver.

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

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) 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) 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);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Step 2

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...