Today I am going to show how can we update Activity using android.os.ResultReceiver. What we need is just create and inner class inside an Activity that extends ResultReceiver and override its onReceiveResult() methods that will be called while sending data from Service class and inside this method we can update UI components.
What I will show in Demo?
I will just create an Activity with a TextView and update the TextView with current seconds of time.
So, create an Activity with main.xml having a TextView. Also, an inner class that extends ResultReceiver and a class that extends Runnable to be used for runOnUiThread.
public class ResultReceiverDemoActivity extends Activity{
Intent intent;
TextView txtview;
MyResultReceiver resultReceiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultReceiver = new MyResultReceiver(null);
txtview = (TextView) findViewById(R.id.txtview);
intent = new Intent(this, MyService.class);
intent.putExtra("receiver", resultReceiver);
startService(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(intent);
}
class UpdateUI implements Runnable
{
String updateString;
public UpdateUI(String updateString) {
this.updateString = updateString;
}
public void run() {
txtview.setText(updateString);
}
}
class MyResultReceiver extends ResultReceiver
{
public MyResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if(resultCode == 100){
runOnUiThread(new UpdateUI(resultData.getString("start")));
}
else if(resultCode == 200){
runOnUiThread(new UpdateUI(resultData.getString("end")));
}
else{
runOnUiThread(new UpdateUI("Result Received "+resultCode));
}
}
}
}
As, you can see there is nothing much in the above code just a simple one. The new thing about you would be the class that extends ResultReceiver. It is having an overrided method onReceiveResult(int resultCode, Bundle resultData) with parameters resultCode and Bundle. These two parameters we will pass from the Service class using send(resultCode, Bundle resultData) of ResultReceiver which will be pass to onReceiveResult(int resultCode, Bundle resultData) where we can update the UI.
Also, one more important thing is that you might have seen that I am passing a putExtra to Service class as
intent.putExtra("receiver", resultReceiver); where resultReceiver is the instance of MyResultReceiver class that extends ResultReceiver. We will get the putExtra in the Service class and use the same instance to send data from Service to Activity using send(resultCode, Bundle resultData).
Now, lets add the Service class that is also a simple one having a Timer with 1 second.
public class MyService extends Service{
Timer timer = new Timer();
MyTimerTask timerTask;
ResultReceiver resultReceiver;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
resultReceiver = intent.getParcelableExtra("receiver");
timerTask = new MyTimerTask();
timer.scheduleAtFixedRate(timerTask, 1000, 1000);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
Bundle bundle = new Bundle();
bundle.putString("end", "Timer Stopped....");
resultReceiver.send(200, bundle);
}
class MyTimerTask extends TimerTask
{
public MyTimerTask() {
Bundle bundle = new Bundle();
bundle.putString("start", "Timer Started....");
resultReceiver.send(100, bundle);
}
@Override
public void run() {
SimpleDateFormat dateFormat = new SimpleDateFormat("s");
resultReceiver.send(Integer.parseInt(dateFormat.format(System.currentTimeMillis())), null);
}
}
}
So, simply we are getting the putExtra of ResultReceiver's instance using resultReceiver = intent.getParcelableExtra("receiver"); inside onStartCommand() to use it further for sending the data to Activity. You can send any data to Activity using send(resultCode, Bundle resultData) method of ResultReceive, you can send an error message also with the same method checking the resultCode.
Source code can be found here.
What I will show in Demo?
I will just create an Activity with a TextView and update the TextView with current seconds of time.
So, create an Activity with main.xml having a TextView. Also, an inner class that extends ResultReceiver and a class that extends Runnable to be used for runOnUiThread.
public class ResultReceiverDemoActivity extends Activity{
Intent intent;
TextView txtview;
MyResultReceiver resultReceiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultReceiver = new MyResultReceiver(null);
txtview = (TextView) findViewById(R.id.txtview);
intent = new Intent(this, MyService.class);
intent.putExtra("receiver", resultReceiver);
startService(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(intent);
}
class UpdateUI implements Runnable
{
String updateString;
public UpdateUI(String updateString) {
this.updateString = updateString;
}
public void run() {
txtview.setText(updateString);
}
}
class MyResultReceiver extends ResultReceiver
{
public MyResultReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if(resultCode == 100){
runOnUiThread(new UpdateUI(resultData.getString("start")));
}
else if(resultCode == 200){
runOnUiThread(new UpdateUI(resultData.getString("end")));
}
else{
runOnUiThread(new UpdateUI("Result Received "+resultCode));
}
}
}
}
As, you can see there is nothing much in the above code just a simple one. The new thing about you would be the class that extends ResultReceiver. It is having an overrided method onReceiveResult(int resultCode, Bundle resultData) with parameters resultCode and Bundle. These two parameters we will pass from the Service class using send(resultCode, Bundle resultData) of ResultReceiver which will be pass to onReceiveResult(int resultCode, Bundle resultData) where we can update the UI.
Also, one more important thing is that you might have seen that I am passing a putExtra to Service class as
intent.putExtra("receiver", resultReceiver); where resultReceiver is the instance of MyResultReceiver class that extends ResultReceiver. We will get the putExtra in the Service class and use the same instance to send data from Service to Activity using send(resultCode, Bundle resultData).
Now, lets add the Service class that is also a simple one having a Timer with 1 second.
public class MyService extends Service{
Timer timer = new Timer();
MyTimerTask timerTask;
ResultReceiver resultReceiver;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
resultReceiver = intent.getParcelableExtra("receiver");
timerTask = new MyTimerTask();
timer.scheduleAtFixedRate(timerTask, 1000, 1000);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
Bundle bundle = new Bundle();
bundle.putString("end", "Timer Stopped....");
resultReceiver.send(200, bundle);
}
class MyTimerTask extends TimerTask
{
public MyTimerTask() {
Bundle bundle = new Bundle();
bundle.putString("start", "Timer Started....");
resultReceiver.send(100, bundle);
}
@Override
public void run() {
SimpleDateFormat dateFormat = new SimpleDateFormat("s");
resultReceiver.send(Integer.parseInt(dateFormat.format(System.currentTimeMillis())), null);
}
}
}
So, simply we are getting the putExtra of ResultReceiver's instance using resultReceiver = intent.getParcelableExtra("receiver"); inside onStartCommand() to use it further for sending the data to Activity. You can send any data to Activity using send(resultCode, Bundle resultData) method of ResultReceive, you can send an error message also with the same method checking the resultCode.
Source code can be found here.
Thanks for the tutorial dude.
ReplyDeleteThanks, it is very helpful
ReplyDeleteThanks for the tute. Could you please explain why you would use this method instead of Handlers and Messages?
ReplyDeleteYes, agree with El Niño, your tutorial is Pretty good.
DeleteIf one needs to use the Handler <-> Message way to achieve the same goal, then here it goes:
----
In your UI Class, you must define another nested static class which extends the Handler Class, like:
public static class TestHandler extends Handler
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch(msg.what) // msg.what is an identifier (int)
{
// Do your stuff for each message received
}
}
}
Then, in your Service Class, you instantiate that static class as a Handler:
(You can use the specific class, like: MyUI.TestHandler, or you can just do a simple Uppercast to use a Handler in a straightforward manner.)
Like:
public class BackgroundService extends Service
{
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Handler hand = new MyUI.TestHandler();
Message msg = new Message();
msg.what = MyUI.sServAtivo; // 1
hand.sendMessageDelayed(msg, 4000); // Just to have to wait
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
}
---
Just bear in mind:
If you do it this way, you cannot directly access UI components, "only the UI can touch its views" someone may say. If you need to, you'll have to implement some listeners or, maybe, extend your UI activity and implement the changes inside another Thread.
It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in android programming your post help me a lot.Thanks for your informative article. Best Android Training in chennai
ReplyDeleteWow, I have gone through the written program and I have reminded myself the basic programming skills and knowledge I learned while in college. I will save this page so that I can go though the program slowly and understand the syntax. Apart from loving to program, I write articles and m articles can be read by clicking on How to Develop Good Research Writing Skills.
ReplyDeleteMarvelous site all content was very quality and I'm seeing the most of the content is really well.Great article.
ReplyDeleteSelenium Training in Chennai
Best Selenium Training Institute in Chennai
Selenium Training in Chennai
Even though we can claim that we can generate our own ideas and use them to develop our own projects, secondary sources are also very useful. There is that kind of information which you will only obtain by reading such articles. this is the kind of information which I daily desire to have. Ask for Supply Chain Management Homework Help from experts.
ReplyDeleteI tried serviceconnection and broadcasterreceiver, but all failed.
ReplyDeleteThis is really great!
Thank you very much.
Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.
ReplyDeleteAWS Training in Bangalore | Amazon Web Services Training in Bangalore
Amazon Web Services Training in Pune | Best AWS Training in Pune
It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
ReplyDeleteDigital Marketing online training
full stack developer training in pune
full stack developer training in annanagar
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
ReplyDeleteData Modeling Training From India
Mule ESB Training From India
Sailpoint Training From India
This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
ReplyDeleteBest Abinitio Online Training From India
Best Microsoft Azure Online Training From India
Best App V Online Training From India
Nice it seems to be good post... It will get readers engagement on the article since readers engagement plays an vital role in every blog.i am expecting more updated posts from your hands.
ReplyDeleteAWS Selfplaced Videos
Golden Gate Selfplaced Videos
Powershell Selfplaced Videos
Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
ReplyDeleterpa training in velachery| rpa training in tambaram |rpa training in sholinganallur | rpa training in annanagar| rpa training in kalyannagar
Really very nice blog information for this one and more technical skills are improve,i like that kind of post.
ReplyDeleteJava training in Indira nagar | Java training in Rajaji nagar
Java training in Marathahalli | Java training in Btm layout
Really you have done great job,There are may person searching about that now they will find enough resources by your post
ReplyDeleteData Science training in kalyan nagar | Data Science training in OMR
Data Science training in chennai | Data science training in velachery
Data science training in tambaram | Data science training in jaya nagar
The blog was more innovative… waiting for your new updates…
ReplyDeleteAndroid Course in Chennai
Android Course in Coimbatore
Android Course in Bangalore
Android Course in Madurai
Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing...
ReplyDeleteamazon web services training in bangalore
aws tutorial for beginners
ReplyDeleteIt is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
http://chennaitraining.in/test-complete-training-in-chennai/
http://chennaitraining.in/load-runner-training-in-chennai/
http://chennaitraining.in/jmeter-training-in-chennai/
http://chennaitraining.in/soapui-testing-training-in-chennai/
http://chennaitraining.in/mobile-application-testing-training-in-chennai/
http://chennaitraining.in/html-training-in-chennai/
Android application is a best one to earn more money. For any android app development visit cloudi5, it is a best android app development company in coimbatore
ReplyDeleteNice article! I found some useful information in your blog
ReplyDeletemobile app developement companies in Singapore
Top android app development companies in Sydney
nice blog....
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
very informative...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
very good topic...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
nice article...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
its very informative...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
nice blog...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
nice...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
nice blog....
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
Awesome blog...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
nice blog...
ReplyDeleteArtificial Intelligence Training in Chennai | Certification | ai training in chennai | Artificial Intelligence Course in Bangalore | Certification | ai training in bangalore | Artificial Intelligence Training in Hyderabad | Certification | ai training in hyderabad | Artificial Intelligence Online Training Course | Certification | ai Online Training | Blue Prism Training in Chennai | Certification | Blue Prism Online Training Course
Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...
ReplyDeleteDigital Marketing Training in Chennai
Digital Marketing Training in Bangalore
Digital Marketing Training in Delhi
Digital Marketing Online Training