Recently, I needed to update an activity in Android with data I gathered from a background Service. I couldn’t find any decent examples on the web or StackOverflow, so I decided to put one together. I really like when someone has a complete working sample, so I will provide that as well you can download the source code from Github at the end of this article. The Android project is very simple, with just two classes, the activity and the background service. We’ll take a look first at the background service to see how the data is generated.
The first thing that needs to be done is to create a string called BROADCAST_ACTION, this is simply a string that identifies what kind of action is taking place. Most of the time, it’s common to use the package name with the kind of action added to the end, so we’ll do that here. The next step is to create a handler that will be used to broadcast our data every 5 seconds. It’s better to use a Handler instead of Timer because a Timer creates a new thread.
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
In onCreate, I’ve created a Intent and passed the BROADCAST_ACTION to the constructor of the intent. Notice that the Intent was defined as a global variable above. The intent will be called repeatedly in the Handler below and there is no reason to create a new intent every 5 seconds, so I’ll create it once here.
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
In onStart, first we call removeCallbacks to remove any existing callbacks to the handler and make sure we don’t get more callbacks than we want. Then we call our handler with a one second delay. This will start our runnable object below.
@Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
Our runnable object creates a new thread, performs whatever code is in the run method and then shuts down. In the run method, we do two things call the DisplayLoggingInfo method and then calls handler.postDelayed again but this time with a 5 second delay. This is how the repeating timer is created. One of the things that is nice about doing it this way, is that you can put a variable in place of 5000 and that way you can externally control the interval between call to the runnable object.
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 5000); // 5 seconds
}
};
In the following method, we add some data to our intent that was created above. I’m just adding the date and a simple counter that increments itself. Then we call sendBroadcast with that intent which sends a message and whoever is registered to receive that message will then get it.
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("time", new Date().toLocaleString());
intent.putExtra("counter", String.valueOf(++counter));
sendBroadcast(intent);
}
At this point, the Service is completed and now it’s time to take a look at our Activity and see how we consume and display our data. The first thing we’ll do is create an intent with the name of the Service class. This will be passed to startService and stopService.
public class BroadcastTest extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
}
Now, we’ll create a BroadcastReceiver to receive the message that is going to be broadcast from the Service above. The BroadcastReceiver has one method, onReceive, it gets called and then the BroadcastReceiver object is destroyed. In the onReceive method, we call updateUI passing in our intent which is holding the data to display.
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
In onResume and onPause, we start and stop our Service. This happens when the screen (Activity) displays and goes away. We also register our BroadcastReceiver by passing in an IntentFilter. Do you see that the IntentFilter is using the same static string, BROADCAST_ACTION, that we created in the Service above. This is how we identify the message that is broadcast. in onPause, we also make sure that we call unregisterReceiver to stop listening for broadcasts.
@Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
This last bit of code is pretty straight forward. We get our data out of the intent and set our two TextViews with the data. They will be updated every 5 seconds.
private void updateUI(Intent intent) {
String counter = intent.getStringExtra("counter");
String time = intent.getStringExtra("time");
Log.d(TAG, counter);
Log.d(TAG, time);
TextView txtDateTime = (TextView) findViewById(R.id.txtDateTime);
TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
txtDateTime.setText(time);
txtCounter.setText(counter);
}
I’ve made the entire project available for download here on GitHub.

How do i listen this into multiple activity?
Thanks, its a nice tutorial, this is what i am looking for ! I have one small question reagrding this. if i want to use broadvasted data on multiple activities then do i need to create the broadcastReciever and need to call register-unregister service for each activity ? or is there any better way to do the same.
Thanks & Regards
Juned
Hi, Thanks for the tutorial, works really well. I just have one question. I want to display random array of boolean values, which will update continuously.
What I did is here:
for(int i =0; i<arrBool.length; i++) {
arrBool[i] = r.nextBoolean();
if (arrBool[i] == true) {
intent.putExtra("extra", Array.getBoolean(arrBool, i));
}
if (arrBool[i] == false) {
intent.putExtra("extra", Array.getBoolean(arrBool, i));
}
}
——————————————–
Now it is not getting that boolean array into BroadcastTest.java. I used textview.setText(ArrBool[]) It is not working. I was able to display one value at a time, but not array. I'd really appreciate if anybody could help me with this.
Thanks
Mayur
Pingback: Modify variable from MainActivity in my Service class then update the TextView with variable : Android Community - For Application Development
Pingback: Use multiple service or do all operations in single service which is preferable? | BlogoSfera
i convey my gratitude for providing this.
Muy interesante!!, Muchisimas gracias 🙂
brilliant! THANKS!
Your are my hero!
This example helped me tremendously for one of my projects. I spent days looking for what I finally found here. Your example is not only easy to understand, but it is only very well explained. Thank you so much.
Flaco sos un genio!!!!!
You are a genius!!!
Thank you so much for this…. I have been trying to update my gps onLocationListener result to the UI for so long now…. this tutorial sorted everything overnight… Now I have a kick ass GPS activity!
Thanks for the tutorial and source. I was going nuts trying to figure out how to run a service like this in my Android application. Best wishes.
Many thanks. This is a great tutorial.
Plz help on my this task sir,
http://stackoverflow.com/questions/18888100/use-broadcast-receiver-using-service
i really want to you thank you
it works goood ! wooow
Service programming is a bit confusing , you provided exactly what I was looking for to understand the thing.
Thank you.
Very helpful! Great tutorial! Many Thanks!
This is excellent. Thank you very much!!!
Great tutorial – well explained and gives an insight on how services and receivers interact.
Thanks a milllion!
Hi nick,
you have explained this tutorial very well and thank you.
I have a question, what if I want to make a tracking application and hide it from the user. If my phone get stolen, my tracking application is still working but it is invincible (to the thief – it literally does not exist anywhere in the phone). So the thief does not aware of the presence of the application but it runs on background and has all the functionality. Also If I want to get the app to change its setting I can do it by dialling a specific number in the dial pad. So the original user can also configure it whenever he wants.
How can I implement this?
Thank You
Hi Isuru
I have heard that there are ways to hide apps but it’s not something I have looked into. Most people would immediately think that an app that was hidden was trying to spy on people in some way. I found this on stackoverflow but it’s not something I can vouch for:
http://stackoverflow.com/questions/8802340/is-it-possible-to-hide-a-particular-application-from-user
Isuru, one thing I’ve been wanting to mention to you. I’m rebuilding one of my websites:
https://www.mycelltracker.com/
If you’re interested, you could possibly help me rebuild it. Think about it and talk to your professors about it. It could be a lot of fun and I bet you would learn a heck of a lot. Let me know if you’re interested.
n
Hi nick,
Glad to hear that you are rebuilding your website. And I am really like to help in whatever way that I can. But I am no genius like you, ok 🙂
Also thank you very much for helping me out with my problems, and I want to return the favour. So about my project, I told you that I am completely new to android, so I took a beginning tutorial to learn the basics and now I am somewhat familiar with android. Also I’ve researched a lot and (also the link you have provided) I managed to launch my app using dial pad (using broadcast receivers) and I can hide the app from app-drawer by commenting out the lines,
form the manifest, but still I couldn’t able to hide the app completely from the system. I think it is impossible, no? So I thought of an alternative like disguise the app so nobody thinks that as a spy/tracking app.
Anyway, the hard part is still ahead of me, which is the gps tracking part, So I am going through your initial tutorial and will contact you if I got any problems, I am pretty sure that I will have a lot of problems. How about your other tutorials? are they coming along? It will be really helpful to follow than.
Thank You
IC
Sounds interesting, whatever it is you are building. As far as tutorials, let me know what you are thinking of and I will consider writing one if it fits in with the overall goals of the websmithing website and if I have the time. Right now I’m working full time on getting the Gps Tracker wordpress plugin working. I’m new to writing wordpress plugins and it’s very much a challenge for me but I’m really enjoying it. Let me know how it’s coming along.
n
Isuru
Just out of curiousity, why are you trying to hide the application on the phone?
Nick
Great work!! You saved my day.
Great tutorial!
You saved my day!
A lot of thanks, its very helpful and quite easy to understand!
I am going to demonstrate about how to go back to previous activity without reloading and refreshing the activity every time.
When we use Intent class and start activity method to back previous activity then our application refreshed again as well as takes time to reload. For use start activity method you should to know the name of previous activity. For all these reasons you can follow my steps which steps will be saved your code and time as well as your application will be run fast.
for full implementation of Go back previous activity without Reloading or Refreshing activity in Android go here: http://www.mindstick.com/Articles/853786d2-a282-4f15-a16d-5861832557d9/Go%20back%20previous%20activity%20without%20Reloading%20or%20Refreshing%20activity%20in%20Android
Kamlakar
My Android application only has one activity. Why are you posting this here?
Nick
Thank you for this great tutorial!
Really a help! Thanks
Great Tutorial…..
Thankyou, Thankyou, Thankyou, Thankyou, Thankyou, Thankyou, Thankyou, Thankyou, !!
Hi!
Why You are stopping and starting the service in the onpause, onresume?
I would like to keep the background service running also when the activity is paused/destroyed.
Thank you
Camillo
Hi Camillo
I’m not sure what you are talking about. Can you please show me a specific line number you are having problems with?
https://github.com/nickfox/GpsTracker/tree/master/phoneClients
n
i want to update UI whenever there is a change in my remote database. How to do it?
What UI and what remote database?
n
I am getting some data from database on my android activity. Data is hosted some where remotely. how to get updated data whenever there is change in database without refreshing my android screen.
Did you try the auto refresh button?
n
Thanks for sharing!! It helped me a lot!!
Can I call registerReceiver() before startService()?
Likewise, can I call stopService() before unregisterReceiver()?
Thank you.
i wanna like this video tutorial,,
Thanks a lot for all the help
Hi,
i wanted to popup alert dialog box with yes/no buttons , after login to the application in any activity this dialog may occur(i will put timer for 20secs to display alert) how can i do this?
Hi,
i wanted to popup alert dialog box with yes/no buttons , after login to the application in any activity this dialog may occur(i will put timer for 20secs to display alert) how can i do this, please suggest?
Hi,
i wanted to popup alert dialog box with yes/no buttons , after login to the application in any activity this dialog may occur(i will put timer for 20secs to display alert) how can i do this, please help?
Hi Nick,
This can be a silly question… After I logged in, I want to display the detailed information screen (let’s say CustomerDetails screen) whose data was filled and stored in DB before, just like you display a detailed screen in Window. In Android, I am supposed to invoke the CustomerDetails activity but it shows a blank screen unless you invoke the webservice and fill it up with data from the webservice, (you need to do all steps similarly when you saved the customer information to DB). My question is: Is there any other more efficient way in Android (like you develop the Create New and then display Edit in window)?
One suggestion, if you have multiple Actions, then you want to check against them in the onReceive method. In this example there is only 1 Action (BROADCAST_ACTION) so it’s not necessary:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (BroadcastService.BROADCAST_ACTION.equals(intent.getAction())) {
updateUI(intent);
}