Sunday, October 21, 2012

communication between android widget and application

Widget is a convienent feature in android that gives users quick access to frequently used application functions. A example is the power control widget. It helps us quickly toggling accessories such as WIFI, GPS power to conserve battery, without tedious operations.
android power control widget
When we plan to provide widget in our own application, an important thing to think about is the communication model between the widget and application. In a simiplified manner, the commucation model is shown below.
communication model diagram
The widget is shown on home screen(which is a AppWidgetHost), and user can interact(e.g., touch) with the widget. The result of the interaction is either showing an activity to the user to display more information, or controlling the state of a background service. Meanwhile, the background service may proactively update the widget to inform user current state. The communication model is bidirectional.

Launch activity from widget

To launch an activity from widget, we can use RemoteViews's setOnClickPendingIntent method to set a intent for the target button. Once the button is clicked, the intent will be sent to start desired activity. The snippet below shows how to do this in AppWidgetProvider.
 1 import android.app.PendingIntent;
 2 
 3 import android.appwidget.AppWidgetManager;
 4 import android.appwidget.AppWidgetProvider;
 5 
 6 import android.content.Context;
 7 import android.content.Intent;
 8 
 9 import android.widget.RemoteViews;
10 
11 public class GestureAppWidgetProvider extends AppWidgetProvider {
12 
13         public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
14             final int N = appWidgetIds.length;
15 
16             // Perform this loop procedure for each App Widget that belongs to this provider
17             for (int i=0; i<N; i++) {
18                 int appWidgetId = appWidgetIds[i];
19 
20                 // Create an Intent to launch Activity
21                 Intent intent = new Intent(context, MainActivity.class);
22                 PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
23 
24                 // Get the layout for the App Widget and attach an on-click listener
25                 // to the button
26                 RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget);
27                 views.setTextColor(R.id.startRecord, Color.GREEN);
28                 views.setOnClickPendingIntent(R.id.startRecord, pendingIntent);
29 
30                 // Tell the AppWidgetManager to perform an update on the current app widget
31                 appWidgetManager.updateAppWidget(appWidgetId, views);
32             }
33         }
34 }

Send message to service from widget

The skeleton of code to send message to a service is pretty much the same as the snippet above. The change we need to make is substitute PendingIntent.getActivity with PendingIntent.getBroadCast. The result is once we clicked the button, a broadcast Intent will be sent, and our AppWidgetProvider(which is a subclass of BroadcastReceiver) will get this intent. Thie AppWidgetProvider runs in our application's process, so it can send the message to our service with StartService.
 1 public class WeatherWidgetProvider extends AppWidgetProvider {
 2     public static String REFRESH_ACTION = "com.example.android.weatherlistwidget.REFRESH";
 3 
 4     @Override
 5     public void onReceive(Context ctx, Intent intent) {
 6         final String action = intent.getAction();
 7         if (action.equals(REFRESH_ACTION)) {
 8             // send message to background service via startService here
 9             // ..............
10         }
11         super.onReceive(ctx, intent);
12     }
13 
14     @Override
15     public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
16         for (int i = 0; i < appWidgetIds.length; ++i) {
17             final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
18             rv.setRemoteAdapter(appWidgetIds[i], R.id.weather_list, intent);
19 
20             // Set the empty view to be displayed if the collection is empty.  It must be a sibling
21             // view of the collection view.
22             rv.setEmptyView(R.id.weather_list, R.id.empty_view);
23 
24             // Bind the click intent for the refresh button on the widget
25             final Intent refreshIntent = new Intent(context, WeatherWidgetProvider.class);
26             refreshIntent.setAction(WeatherWidgetProvider.REFRESH_ACTION);
27             final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0,
28                     refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
29             rv.setOnClickPendingIntent(R.id.refresh, refreshPendingIntent);
30 
31             appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
32         }
33         super.onUpdate(context, appWidgetManager, appWidgetIds);
34     }
35 }

Update widget from service

To update a widget from service, we can send a broadcast message from the background service to AppWidgetProvider. Once the AppWidgetProvider receives the message, it tries to fetch current state and calls notifyAppWidgetViewDataChanged function to refresh the widget.
public void onReceive(Context ctx, Intent intent) {
    final String action = intent.getAction();
    if (action.equals(SHOW_NEW_DATA_ACTION)) {
        final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
        final ComponentName cn = new ComponentName(context, WeatherWidgetProvider.class);
        mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.weather_list);
    }
    super.onReceive(ctx, intent);
}

Reference:

android WeatherListWidget sample
Introducing home screen widgets and the AppWidget framework
android appwidget source code
android appwidget service source code

37 comments:

Mark Joseph Villaflor said...

in sending message, how to send broadcast message in other class the onreceive is on the fragment class is this possible ?

markfili said...
This comment has been removed by the author.
Geetha Devi said...

Very informative ..i suggest this blog to my friends..Thank you for sharingAndroid Training

SRI said...

The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.


rpa Training in annanagar

blue prism Training in annanagar

automation anywhere Training in annanagar

iot Training in annanagar

rpa Training in marathahalli

blue prism Training in marathahalli

automation anywhere Training in marathahalli

blue prism training in jayanagar

automation anywhere training in jayanagar

SRI said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

rpa Training in Chennai

rpa Training in bangalore

rpa Training in pune

blueprism Training in Chennai

blueprism Training in bangalore

blueprism Training in pune

rpa online training

SRI said...

Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

automation anywhere training in chennai

automation anywhere training in bangalore

automation anywhere training in pune

automation anywhere online training

blueprism online training

rpa Training in sholinganallur

rpa Training in annanagar

iot-training-in-chennai

blueprism-training-in-pune

automation-anywhere-training-in-pune

SRI said...

Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

rpa Training in tambaram

blueprism Training in tambaram

automation anywhere training in tambaram

iot Training in tambaram

rpa training in sholinganallur

blue prism training in sholinganallur

automation anywhere training in sholinganallur

iot training in sholinganallur

SRI said...

Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

rpa Training in tambaram

blueprism Training in tambaram

automation anywhere training in tambaram

iot Training in tambaram

rpa training in sholinganallur

blue prism training in sholinganallur

automation anywhere training in sholinganallur

iot training in sholinganallur

SRI said...

Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

rpa Training in Chennai

rpa Training in bangalore

rpa Training in pune

blueprism Training in Chennai

blueprism Training in bangalore

blueprism Training in pune

rpa online training

digi mark said...

Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.

rpa Training in Chennai

rpa Training in bangalore

rpa Training in pune

blueprism Training in Chennai

blueprism Training in bangalore

blueprism Training in pune

rpa online training

digi mark said...

All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.

automation anywhere training in chennai

automation anywhere training in bangalore

automation anywhere training in pune

automation anywhere online training

blueprism online training

rpa Training in sholinganallur

rpa Training in annanagar

iot-training-in-chennai

blueprism-training-in-pune

automation-anywhere-training-in-pune

digi mark said...

It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command

rpa Training in tambaram

blueprism Training in tambaram

automation anywhere training in tambaram

iot Training in tambaram

rpa training in sholinganallur

blue prism training in sholinganallur

automation anywhere training in sholinganallur

iot training in sholinganallur

digi mark said...

This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

rpa Training in annanagar

blue prism Training in annanagar

automation anywhere Training in annanagar

iot Training in annanagar

rpa Training in marathahalli

blue prism Training in marathahalli

automation anywhere Training in marathahalli

blue prism training in jayanagar

automation anywhere training in jayanagar

digi mark said...

This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

rpa Training in annanagar

blue prism Training in annanagar

automation anywhere Training in annanagar

iot Training in annanagar

rpa Training in marathahalli

blue prism Training in marathahalli

automation anywhere Training in marathahalli

blue prism training in jayanagar

automation anywhere training in jayanagar

john jersy said...

The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
Click here:
angularjs training in sholinganallur
Click here:
angularjs training in btm

nivatha said...

Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.

Data Science Training in Chennai
Data science training in bangalore
Data science online training
Data science training in pune
Data science training in kalyan nagar
selenium training in chennai

simbu said...

Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts
java training in chennai | java training in bangalore

java online training | java training in pune

java training in chennai | java training in bangalore

vishnu said...

It is very useful to me. Keep sharing this kind of useful information.

IoT Certification | Internet of Things Training in Chennai

john jersy said...

I am so proud of you and your efforts and work make me realize that anything can be done with patience and sincerity. Well, I am here to say that your work has inspired me without a doubt.
python training in chennai
python training in Bangalore

thulasi ragini said...

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.is article.
python training institute in chennai
python training in velachery
python training institute in chennai

Sheela said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
DevOps online Training|DevOps Training in USA
Devops Training in Chennai
Devops Training in Bangalore

Sheela said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
Devops Training in Chennai

Devops Training in Bangalore

Devops Training in pune

shines rose said...

Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
Blueprism training in btm

Blueprism online training

chitra pragya said...

This is a terrific article, and that I would really like additional info if you have got any. I’m fascinated with this subject and your post has been one among the simplest I actually have read.

angularjs Training in bangalore

angularjs Training in btm

angularjs Training in electronic-city

angularjs online Training

angularjs Training in marathahalli

cynthia williams said...

Informative post, thanks for taking time to share this page.
Robotic Process Automation Training in Chennai
Robotic Process Automation Certification
RPA Training in Chennai
AWS Training in Chennai
Angularjs Training in Chennai
ccna Training in Chennai

Vikky cmd said...

I am really happy with your blog because your article is very unique and powerful for new reader.
Click here:
selenium training in chennai
selenium training in bangalore
selenium training in Pune
selenium training in pune
Selenium Online Training

https://rpeszek.blogspot.com/2014/10/i-dont-like-hibernategrails-part-11_31.html

LindaJasmine said...

Interesting Post. I liked your style of writing. It is very unique. Thanks for Posting.

Node JS Training in Chennai
Node JS Course in Chennai
Node JS Advanced Training
Node JS Training Institute in chennai
Node JS Training Institutes in chennai
Node JS Course

Shiva Shakthi said...

The information which you shared is very much intresting. Thanks for sharing the amazing blog.
Web Designing Course in Coimbatore
Web Design Training in Coimbatore
Web Designing Training Institute in Coimbatore
Web Design Training Coimbatore
Best Web Designing Institute in Coimbatore

Sai Elakiyaa said...

Excellent way of expressing your ideas with a clear vision, Keep updating.
Selenium Training in Chennai
Selenium Training
iOS Training in Chennai
Digital Marketing Training in Chennai
core java training in chennai
PHP Training in Chennai
PHP Course in Chennai

Vicky Ram said...

Excellent post! keep sharing such a post

Guest posting sites
Education

Anbarasan14 said...

One of the best blogs that I have read till now. Thanks for your contribution in sharing such a useful information. Waiting for your further updates.

Spoken English Institutes in Bangalore
Spoken English Coacjing Classes near me
English Speaking Classes in Bangalore
Spoken English Chennai
English Classes in Chennai
Spoken English Course in Chennai
Best Spoken English Classes in Chennai

yuva prithika said...

This is really too useful and have more ideas and keep sharing many techniques. Eagerly waiting for your new blog keep doing more.
Aws Training in Bangalore
Aws Course in Bangalore
Best Aws Training in Bangalore
hadoop classes in bangalore
hadoop institute in bangalore
Aws Training Institutes in Bangalore
Aws Certification Training in Bangalore

sharmi chithra said...

It is very excellent blog and useful article thank you for sharing with us, keep posting.

Primavera Training
Primavera p6 Training
Primavera Training Institute in Chennai
Primavera Training Institutes in Chennai

sharmi chithra said...

Nice post. I learned some new information. Thanks for sharing.

Xamarin Training in Chennai
Xamarin Course in Chennai
Xamarin Training
Xamarin Course
Xamarin Training Course
Xamarin Classes
Best Xamarin Course

LindaJasmine said...

Thanks for sharing such an amazing post. Your style of writing is very unique. It made me mesmerized in your words. Keep on writing.

Informatica Training in Chennai
Informatica Training Center Chennai
Best Informatica Training in Chennai
Informatica course in Chennai
Informatica Training center in Chennai
Informatica Training
Learn Informatica
Informatica course

mercyroy said...

Nice way of expressing your ideas with us.
thanks for sharing with us and please add more information's.
Java Classes in Bangalore
Java Training in Ambattur
Java Training in Saidapet
Java Training Institutes in OMR

Harish said...

Thank you for such an informative post. Thank you for sharing with us.

Spark Training Academy Chennai
Apache Spark Training
Spark Training Institute in Adyar
Spark Training Institute in Velachery
Spark Training Institute in Tambaram