Android Broadcastreceiver Within Activity

Android BroadcastReceiver within Activity

What do I do wrong?

The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.

Instead you probably want to startActivity ToastDisplay from the first activity?

BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).

There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in
BroadcastReceiver documentation:

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.

broadcast receiver inside activity

BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// DO YOUR STUFF
}
}

IntentFilter filter = new IntentFilter();

in onResume: (so you receive only while in foreground)

filter.addAction(/* the action you want to receive */);
registerReceiver(receiver, filter);

in onPause: (the try catch is to fix a bug in unregister in case it is called twice)

try {
unregisterReceiver(receiver);
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("Receiver not registered")) {
// Ignore this exception. This is exactly what is desired
Log.w(TAG,"Tried to unregister the reciver when it's not registered");
} else {
// unexpected, re-throw
throw e;
}
}

Calling a Activity method from BroadcastReceiver in Android

try this code :

your broadcastreceiver class for internet lost class :

public class InternetLostReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("INTERNET_LOST"));
}
}

in your activity add this for calling broadcast:

public class TestActivity  extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

registerReceiver(broadcastReceiver, new IntentFilter("INTERNET_LOST"));
}

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// internet lost alert dialog method call from here...
}
};

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
}

How to pass data from BroadcastReceiver to Activity without in onCreate()

There is a very simple design pattern you can use here to ease communication between your classes and also decouple your code: publisher/subscriber. My favorite library for this is EventBus:

First, add to your build.gradle file:

compile 'org.greenrobot:eventbus:3.0.0'

Then, create a simple POJO - Plain Old Java Object like this:

public class OnReceiverEvent{
private String phoneNumber;

public OnReceiverEvent(String phone){
this.phoneNumber = phone;
}

public String getPhoneNumber(){
return phoneNumber;
}
}

Next, by making your Receiver class a publisher, and your Activity a subscriber, you should be able to easily pass the information to your activity like this:

//inside your PhoneStateReceiver class when you want to pass info

EventBus.getDefault().post(new OnReceiverEvent(phoneNumber));

Next, inside your activity, simply do this:

//onStart
@Override
public void onStart(){
super.onStart();
EventBus.getDefault().register(this);
}

//onStop
@Override
public void onStop(){
super.onStop();

EventBus.getDefault().unregister(this);
}

Finally, handle the posted data i.e phoneNumber value:

@Subscribe
public void onPhoneNumberReceived(OnReceiverEvent event){
//get the phone number value here and do something with it

String phoneNumber = event.getPhoneNumber();

//display or something?
}

UPDATE

If you have another Event that you want this activity to subscribe to, simply create a method like you did in the first one using the @Subscribe annotation.

@Subscribe
public void onSomeOtherEvent(EventClassName event){
//get the variables here as usual;
}

This is the easiest way to pass the data from your receiver to your activity without having to worry about starting the activity over and over!

I hope this helps and good luck!

BroadcastReceiver in activity

You should use the defined constants, not string values :

IntentFilter(Intent.ACTION_POWER_CONNECTED)

instead of :

IntentFilter("ACTION_POWER_CONNECTED")

call activity method from broadcast receiver

Thanks @Manishika. To elaborate, making the Broadcastreceiver dynamic, instead of defining it in the manifest, did the trick. So in my broadcast receiver class, i add the code :

MainActivity main = null;
void setMainActivityHandler(MainActivity main){
this.main=main;
}

In the end of the onReceive function of the BroadcastReceiver class, I call the main activity's function :

main.verifyPhoneNumber("hi");

In the main activity, I dynamically define and register the broadcast receiver before sending the sms:

SmsReceiver BR_smsreceiver = null;
BR_smsreceiver = new SmsReceiver();
BR_smsreceiver.setMainActivityHandler(this);
IntentFilter fltr_smsreceived = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(BR_smsreceiver,fltr_smsreceived);


Related Topics



Leave a reply



Submit