Android – using Broadcast receiver from Activity

Featured Image © ColinBroug@sxc.hu

Let’s play a little with BroadcastReceiver: we will try to send a message from Android service we made to Activity and log that message.

Let’s use our Android service tutorial project from one of my earlier articles.

First of all we need to define private variable in our Activity:

//...
 
public class AndroidservicetutorialActivity extends Activity {
 
	private BroadcastReceiver mReceiver;
 
//...

Then we override methods onResume() where our broadcast receiver will be registered and also onPause() where will our receiver be unregistered:

//AndroidservicetutorialActivity.java
//...
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
 
		IntentFilter intentFilter = new IntentFilter(
				"android.intent.action.MAIN");
 
		mReceiver = new BroadcastReceiver() {
 
			@Override
			public void onReceive(Context context, Intent intent) {
				//extract our message from intent
				String msg_for_me = intent.getStringExtra("some_msg");
				//log our message value
				Log.i("InchooTutorial", msg_for_me);
 
			}
		};
		//registering our receiver
		this.registerReceiver(mReceiver, intentFilter);
	}
 
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//unregister our receiver
		this.unregisterReceiver(this.mReceiver);
	}
//...

Now we can try from our service (onStart) send a broadcast message and we will see what is happening in LogCat window:

//firstService.java
package com.inchoo.tutorial;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
 
public class FirstService extends Service{
 
	private static String TAG = "Inchoo.net tutorial";
 
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
 
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Log.d(TAG, "FirstService started");
 
		Intent i = new Intent("android.intent.action.MAIN").putExtra("some_msg", "I will be sent!");
		this.sendBroadcast(i);
 
		this.stopSelf();
	}
 
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "FirstService destroyed");
	}
 
}

From our service, we are sending message to our activity, and that can be seen in LogCat:


14 comments

  1. hey
    can you tell me how i can pass that data to fragment ?
    i mean i want broadcasted data in fragment for example – i have A activity which hold 2 fragments fragment B > c. so how can i pass data to fragment c ?

  2. Hi Darko Goles,

    Thank you for this… i am trying trying to create an app.. where my broadcast receiver should monitor the network status when the user is on call…and it should notify an error if the network goes out when the user is on the middle of the call… can i follow the same approach???

  3. I got the general idea about Broadcast Receivers from this tutorial. But suppose i want to catch power button click from broadcast receiver, how can i do it? can you please show me an example? (I am a newbie in android programming. Any help would be appreciated).

  4. @Darko Goles, thanks for the quick reply. Your tutorial is very well explained.

    I was wondering how can you notify an Activity when it is onPause and has previously launched an IntentService waiting for it to finish.

    Let’s suppose you update the UI according to a network response made by an IntentService. The Activity launches the IntentService, activity goes to background (onPause is called), IntentService finishes and wants to notify UI. If broadcast receiver is not attached, the activity will not receive the response. For this scenario I have been looking around for a robust solution and came up with these possibilities:
    – Handle Activity-IntentService communication with StickBroadcast in order for the activity to get the last broadcast sent by the IntentService when it comes to foreground (very hacky solution I think)
    -Handle Activity-Service communication binding the Activity to the Service and querying the Service to know if it has finished operation (binding makes source code grow up a lot i think and seems way to much effort)
    – Handle Activity-IntentService communication and operation on a worker Fragment (setting fragment to setRetainInstance(true). I think this approach is the convenient one but comes with too much effort also.

    According to your experience, which of these possibilities is the correct one? If none, which one do you prefer to use? Thanks.

  5. How can the activity receive the broadcast if it is onPause()? If the service has dispatch a notification that it has stopped working and the Activity is onPause(), how does the activity knows the service status if it has unregistered the receiver? thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.