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

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.

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

Related

Broadcast Receiver class and registerReceiver method

Hi i am trying to understand Broadcast Receiver , i went through many sample codes , but still have some doubts. I wanted to know when we have to extend the Broadcast Receiver class and when should we use registerReceiver() method and when should we create object for BroadcastReceiver. In some programs i came across registerReceiver methods being used but without extending the Broadcast Receiver class. I also wanted to know how the onReceive method gets called.
Which approach should be used when?
here is the registerReceiver method:
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
........
}
}
}, new IntentFilter(SENT));
Object being created for BroadcastReceiver:
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
.................
}
};
Android has intent action for broadcast receiver. BroadCast receiver will be trigger when it listen any action which registered within it.
Now we will take one example :
That we need to listen the action of "whenever any bluetooth device connect to our device". For that android has it fix action android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED
So you can get it via manifest & registration also
BY Manifest Registration:
Put this in your manifest
<receiver android:name="MyBTReceiver">
<intent-filter>
<action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED" />
</intent-filter>
</receiver>
Create MyBTReceiver.class
public class MyBTReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")){
Log.d(TAG,"Bluetooth connect");
}
}
}
That was the simplest broadcast Receiver.
Now,
if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). You can also register it within your existing class file. you also need to unregister it onDestroy().
here, you dont need any broadcast registration in manifest except activity registration
For example
public class MainActivity extends Activity {
IntentFilter filter1;
#Override
public void onCreate() {
filter1 = new IntentFilter("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED");
registerReceiver(myReceiver, filter1);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")) {
Log.d(TAG,"Bluetooth connect");
}
}
};
#Override
public void onDestroy() {
unregisterReceiver(myReceiver);
}
}
In both cases BroadcastReceiver will be extended. In your second example you create so called anonymous class. New class has no specific name, that is why it's called so. Anyway this new class extends BroadcastReceiver and overrides onReceive() method.
Now back to your question. There are two kinds of receivers - statically and dynamically defined ones.
If you declare your receiver in AndroidManifest file, then it is statically defined. In this case you need to refer to a class implementing BroadcastReceiver by name. As you can see, you cannot use an anonymous class, because the last has no name. You have to explicitly implement a receiver. It's worth to mention, that in this case you do not use registerReceiver() method. Android does it for you automatically.
If you declare receivers dynamically (for instance in activity's onResume() method), then you can use anonymous class for that. To register a receiver you call registerReceiver() method. You can also use a named class too. Both options are valid in this case.
Hope this explains the difference.
In both case you are creating object.But in first case there is not any reference for
the receiver object so it can not be unregistered later but second one has so it can be
unregistered after registering object using below methods:
registerReceiver(intentReceiver );
unregisterReceiver(intentReceiver );

Explicit addressing an Intent to a dynamically broadcast receiver

i am new to Android and trying to understand the communication between apps.
I am trying to write 3 little apps which can communicate with each other. If you want to sent a message to everybody you just use an implicit broadcast.
implicit Intent intent.setAction("com.example.myChatMessage")
if you want to adress only 1 specifc receiver i did it with
explicite Intentintent.setComponent("com.example.test.android.broadcastreceiver.b",
"com.example.test.android.broadcastreceiver.b.myBroadcastReceiver")
this works, when the broadcast receiver is a seperate class and defined in the AndroidManifest.xml.
My Question: Is it possible to explicit adress a dynamicall registered broadcast receiver?
package com.example.test.android.broadcastreceiver.b;
public class MainActivity extends Activity {
private final IntentFilter intentfilter = new IntentFilter("com.example.myChatMessage");
private myBroadcastReceiver broadcastreceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcastreceiver = new myBroadcastReceiver();
registerReceiver(broadcastreceiver, intentfilter);
}
public static class myBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.d("message", "B received: "+message);
}
}
}
It receives all implicit broadcasts but no explicit one - i don't know hot to adress it. Can you help me?
It does not appear possible to send an explicit intent to a dynamically registered broadcast receiver. Registering the receiver in AndroidManifest.xml is the only way.
If you dynamically register a BroadcastReceiver – by calling Context.registerReceiver() – you supply a BroadcastReceiver instance ... If you try to send an Intent to the receiver by naming the class of the BroadcastReceiver, it will never get delivered .. The Android system will not match the Intent you declared to the class of the BroadcastReceiver instance you registered.
Source: http://onemikro2nd.blogspot.com/2013/09/darker-corners-of-android.html

Update the UI of the calling activity or start a new activity when the alarm is triggered from a broadcast receiver

I am writing an alarm code and using a broadcast receiver. I am able to receive the broadcast receiver. but now I want to come back to the calling activity and update the UI of my activity. I am not able to this.
I used the following code in my activity but it is never executing that code.
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I am back!!", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(myBroadcastReceiver);
}
#Override
protected void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter("com.test.Main");
registerReceiver(myBroadcastReceiver, intentFilter);
}
in the manifest file I have included the following, here gotAlarm is the broadcast receiver file
<receiver android:name=".gotAlarm"
android:enabled="true">
</receiver>
gotAlarm file is one which gets called from the pending intent of the alarm set
public class gotAlarm extends BroadcastReceiver {
public void onReceive(Context context, Intent intent){
Toast.makeText(context, "Wake Up!!", Toast.LENGTH_LONG).show();
}
}
May be I am missing something very basic.
please help.
Two things:
If you dynamically register the receiver via Context.registerReceiver() then you won't receive broadcasts when Activity is paused (or stopped or not-running). If you need to receive broadcasts even when Activity is paused then create a top-level BroadcastReceiver class (as opposed to your inner class) and use <receiver> to register it.
BroadcastReceiver lifecycle docs state that BroadcastReceiver object is alive only during processing of onReceive(). You can not do any async tasks like showing dialogs, etc.. In your case (Activities might not be running and you receive a broadcast) you should use NotificationManager to notify user something happened.
I have dropped this way and I am starting a new activity on receiving broadcast. And I am sending information data from calling activity to broadcast and from broadcast to next activity. This has served the purpose.
Did you register your BroadcastReceiver (you can do this in the 'onResume'-method of your Activity)? Also, you should unregister your BroadcastReceiver in the 'onPause'-method.

Intent not received by activity

I have a main activity that launches a service to do a web search in the background and I would like the main activity to get an intent when the search is done.
In my main activity , I defined a BroadcastReceiver and an Intent Filter to listen to the "end of search" intent:
public class AgeRage extends Activity {
// Listener to all results from background processes
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ImageSearchService.SEARCH_RESULT_ACTION)) {
0);
Toast.makeText(context,"Got " + i + "results", Toast.LENGTH_SHORT).show();
}
else Toast.makeText(context,"unknown intent", Toast.LENGTH_SHORT).show();
}
};
IntentFilter receiverFilter = new IntentFilter ();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Register to image search service messages
receiverFilter.addAction(ImageSearchService.SEARCH_RESULT_ACTION);
registerReceiver(receiver,receiverFilter);
...
In the service , I do the search and when it is done , I send an Intent:
public class ImageSearchService extends IntentService {
...
protected void onHandleIntent (Intent intent) {
... doing search ...
Intent i = new Intent (this,AgeRage.class);
i.setAction (SEARCH_RESULT_ACTION);
i.putExtra(SEARCH_STATUS, (searchStatus ==SearchStatus.DONE) ? true:false);
i.putExtra (SEARCH_RESULT_NUM, totalResultNum);
i.putExtra (SEARCH_ID, searchID);
sendBroadcast (i,null);
}
But, the main activity doesn't get the Intent. I know that the sendBroadcast is being called and the the receiver's OnReceive is not (checked with a debugger).
I assume that since I create the filter dynamically , I do not need to define a filter in the manifest file.
Am I doing something wrong ?
Thanks
Isaac
Ok. Well I just checked mine and we are doing it the same way, however ...
ImageSearchService.SEARCH_RESULT_ACTION
Try doing com.yourpackagename.ImageSearchSrvice.SEARCH_RESULT_ACTION
where SEARCH_RESULT_ACTION is a public static string variable. See if that helps.
I think it must be the naming of the ACTION. Also note that you might want to run tru the breakpoints and just check log. do intent.getAction() and print this out rather than checking inside the if statement. Just always print it out and see. Don't need to break inside a broacast receiver it will crash after a while.

Android Communication between Broadcast Receiver and MainActivity (Send data to activity)

I've a simple Main Activity which has to stop till an SMS is received... How can I launch a method from the MainActivity within the BroadcastReceiver's onReceive() Method?
Is there away with Signal and Wait? Can I pass something with a pending Intent, or how can I implement this communication?
Communication from BroadcastReceiver to Activity is touchy; what if the activity is already gone?
If I were you I'd set up a new BroadcastReceiver inside the Activity, which would receive a CLOSE message:
private BroadcastReceiver closeReceiver;
// ...
closeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//EDIT: receiving parameters
String value = getIntent().getStringExtra("name");
//... do something with value
finish();
}
};
registerReceiver(closeReceiver, new IntentFilter(CLOSE_ACTION));
Then from the SMS BroadcastReceiver you can send out this action:
Intent i = new Intent(CLOSE_ACTION);
i.putExtra("name", "value"); //EDIT: this passes a parameter to the receiver
context.sendBroadcast(i);
I hope this helps?
I had the exact same problem, I tried using intent but i was unsuccessful
The easiest way to use it would be using static methods and static variables
MainActivity.java
public static void stopsms()
{
/*
some code to stop the activity
*/
}
SMSReceiver.java
at the end call this function
MainActivity.stopsms();
It works amazing if your code does not affect when you use static methods and variables. Let me know if you need any help.
The problem with registering a second receiver within the activity, however, is that it will not be persistent like registering in the manifest... thus, although, this solution may work, will only work if the activity is running in background.
it's easy, use interface like that:
1) in your broadcast receiver create an interface.
public interface ChangeListener{
public void functionWhoSendData(String type);
public void etc();
}
and instantiate that interface in your broadcast receiver, use it:
public void onReceive(....
String data=functionWhereYouReceiveYouData();
ChangeListener.functionWhoSendData(data);
}
And in your activity, make it implements your interface

Categories

Resources