Mastering Android Widget Development - Part4
As described in the previous part, we will use a Service to update the appWidget.
So we will have the Service below, which gets the command (right now we have only the update command), ant the appwidgetId, reads the date from sharedPreferences and updates the widget.
- package com.helloandroid.countdownexam
ple; - import java.util.Date;
- import android.app.Service;
- import android.appwidget.AppWidgetMan
ager; - import android.content.Intent;
- import android.content.SharedPreferen
ces; - import android.os.IBinder;
- import android.widget.RemoteViews;
- public class CountdownService extends Service {
- // command strings to send to service
- @Override
- public void onStart(Intent intent, int startId) {
- //a command, to define what to do, will be important only in the next tutorial part, now there is only update command
- int appWidgetId = intent.getExtras().getInt(
- AppWidgetManager.EXTRA_APPWIDGET_ID);
- RemoteViews remoteView = new RemoteViews(getApplicationContext()
- .getPackageName(), R.layout.countdownwidget);
- AppWidgetManager appWidgetManager = AppWidgetManager
- .getInstance(getApplicationContext());
- SharedPreferences prefs = getApplicationContext().getSharedPreferences(
- "prefs", 0);
- long goal = prefs.getLong("goal" + appWidgetId, 0);
- //compute the time left
- left = left - days * (long) (60 * 60 * 24 * 1000);
- left = left - hours * (long) (60 * 60 * 1000);
- left = left - mins * (long) (60 * 1000);
- //put the text into the textView
- remoteView.setTextViewText(R.id.TextView01, days + " days\n" + hours
- + " hours " + mins + " mins " + secs + " secs left");
- // apply changes to widget
- appWidgetManager.updateAppWidget(appWidgetId, remoteView);
- super.onStart(intent, startId);
- }
- @Override
- public IBinder onBind(Intent arg0) {
- // TODO Auto-generated method stub
- return null;
- }
- }
Services must be registered in the AndroidManifest:
- <service android:name=".CountdownService"></service>
The service is started automatically when you call it, but don~t forget to stop it in the AppWidgetProvider onDisable (When all widget instances are deleted):
- context.stopService(new Intent(context,CountdownService.class));
- super.onDisabled(context);
- }
Now all we have to do is to call this Service when we want to update. The following function constructs a PendingIntent with the given parameters to do this. Insert it into the CountdownConfiguration class.
- Intent active = new Intent(context,CountdownService.class);
- active.setAction(command);
- active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
- //this Uri data is to make the PendingIntent unique, so it wont be updated by FLAG_UPDATE_CURRENT
- //so if there are multiple widget instances they wont override each other
- Uri data = Uri.withAppendedPath(Uri.parse("countdownwidget://widget
/id/#"+command+appWidgetId), String.valueOf(appWidgetId)); - active.setData(data);
- return(PendingIntent.getService(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT));
- }
To update the time left every second we will use the AlarmManager class. Insert following method into the CountdownConfiguration class too. This will start and stop the updating of an AppWidget with the given appWidgetId.
- PendingIntent newPending = makeControlPendingIntent(context,CountdownService.UPDATE,appWidgetId);
- if (updateRate >= 0) {
- alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), updateRate, newPending);
- } else {
- // on a negative updateRate stop the refreshing
- alarms.cancel(newPending);
- }
- }
Using this methods, we
- refresh the appWidget when configuration is done (in ok button onclick)
- PendingIntent updatepending = CountdownWidget
- .makeControlPendingIntent(self,
- CountdownService.UPDATE, appWidgetId);
- try {
- updatepending.send();
- } catch (CanceledException e) {
- e.printStackTrace();
- }
- start the Alarmanager in the AppWidgetProvider onUpdate method (for example at first update, or after phone reboot)
- int[] appWidgetIds) {
- for (int appWidgetId : appWidgetIds) {
- setAlarm(context, appWidgetId, UPDATE_RATE);
- }
- super.onUpdate(context, appWidgetManager, appWidgetIds);
- }
- stop the Alarmanager on the AppWidgetProvider onDelete
- for (int appWidgetId : appWidgetIds) {
- setAlarm(context, appWidgetId, -1);
- }
- super.onDeleted(context, appWidgetIds);
- }
New tutorials from Helloandroid
Recent Apps
Android on Twitter
-
@lendzEra (ledz motin)
BaconReader gets major update, adds Android Beam support, scrollable widget and more http://t.co/aTXFOvQb #android
4 min 12 sec ago -
@grenhall (Mattias Grenhall)RT @iphonecruncher2012HP finally caves and offers up TouchPad Kernel Source http://t.co/HwddIG75 #android #googleandroid #android #apps
4 min 15 sec ago -
@lendzEra (ledz motin)
Sony Tablet P started life as a wallet, almost ran Windows http://t.co/qgi6Nrrs #android
4 min 15 sec ago -
@onebadcarr2 (chris)I've just received an achievement: Quick https://t.co/GfeDIsJo #Android #Androidgames
4 min 16 sec ago -
@darren3131 (darren)I've just received an achievement: Logistician https://t.co/Dn9r87yG #Android #Androidgames
4 min 18 sec ago
Poll
Useful resources
Android Development Projects
- Android App wanted immediately by JoePublic
- LIST DATA PROJ by nhammoud
- Nonpublic project #1433932 by subpariq
- Alarm Android Application Design by globalheed
- Simple Album App for Android by ayfonfan
- iOS and Android photo manipulation 'Morph App' by whatwedomedia
- Onsite Software Engineers in Germany by sudhirshree
- Augmented reality by merder99
- Nonpublic project #1433560 by vobla73
- Mobile app coder needed for quick, simple app by Ergometrix




Comments
دردشة سورية دردشة
دردشة سورية
دردشة لبنانية
دردشة عراقية
شات سوري
شات لبناني
دردشة سوريا
دردشة لبنان
شات سوريا
شات لبنان
دردشة السويدي
منتديات السويدي
اغاني عراقية
صور فنانين
الرياضة العراقية
شعراء العراق
نغمات عراقية
اغاني عربية
اغاني كردية
دردشة عراقية
دردشة بنات العراق
دردشة صبايا بغداد
دردشة البصره
دردشة بغداد
دردشة بغدادية
دردشة صبايا بغداد
دردشة شباب العراق
دردشة بنات العراق
دردشة الكرادة
دردشة دمشق
دردشة بيروت
دردشة حلب
دردشة حلب
دردشة عراقية
دردشة العراق
شات عراقي
جات عراقي
دردشه عراقيه
دردشة صبايا لبنان
دردشة بنات لبنان
شات صوتي | دردشة صوتية | كلام
شات صوتي
| دردشة صوتية
|
كلام
| شات كلام
|
دردشة كلام
| دردشة صوتية
|
شات صوتي
| شات
|
Chat Voice
| ahj w,jd
شات صوتي
| دردشة صوتية
|
شات صوتي
| دردشة صوتية
|
دردشه
| دردشة
|
صوتي
| صوتية
|
شات صوتي
| دردشة صوتية
|
شات صوتي
| دردشة صوتية
|
الكلام
| دردشه صوتيه
|
]v]am w,jdm
| ]v]ai w,jdi
شات صوتي
شات صوتي
شات صوتي
Hotels Santiago
They are items of great interest and importance, thanks for the information in your blog. Hotels Santiago
great stuff
your posts are very informative and i enjoy coming back your website all the time
wedding photographer florida
miami ft lauderdale ft myers dj
thanks
thanks for your article its really great and useful
sportbike specifications SKEMA RANGKAIAN Electronic Circuit scolarship wireless car specifications gadget and computer car first look Motorcycle Modification sexi-stars. newlaptop circuits-audio electronic projects auto girl weapons system science kids gadget bikes walpaper mobil-wallpaper MODIFIKASI MOBIL plane-wallpaper celebsexypict artist-scandal sport-cars bikespict motor-modify sexi-model laptopharga gambar-artist fast-superbike autoshowmodel harga-kamera notebook-price diamonds-collections phones-gallery camera-prices home-pic audio-gallery autocarpict living-cares homes life-style
blogs i like
This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles I guess I am not the only one having all the enjoyment here! keep up the good work.
internet radio dj west palm beach
dj boca raton classified ads
web designer florida
Thanks that was great. This
Thanks that was great. This is my favorite blog for my android.
Johney
Android widgets
I don't think I'll ever master the android widgets beat maker software
thank you
Thank you these are really going to help my forklift training business.
Androids
Great android app tutorial online marketing
A very good and informative
A very good and informative article indeed . It helps me a lot to enhance my knowledge, I really like the way the writer presented his views. windows hosting
Substantially the article is
Substantially the article is really the best on this laudable topic. I concur with your conclusions and will eagerly look forward to your future updates.Just saying thank you will not just be enough for the wonderful lucidity in your writing. Bob Dickson // langenfelder alt
Good job! I have found many
Good job! I have found many articles to read but you do a good thing. That is a boy. Thank you so much for sharing the delicious post. Expect your next article. John Herron // Versicherungen
developing
These android widgets are very hard to get the hang of Beverly Hills, Bel Air, Homes
Excellent
Excellent job on the android app development pool plaster repair kit
development
I don't know if I will ever get the hang of android widget development
Android vs iPhone
This is a great post. Thanks!
This trule motivated me today
Very good job on this post. I just can't believe it. rare coin values
This blog is disseminating
This blog is disseminating valuable information to people who are most concerned of the following issues being targeted by this site. Many certainly will keep coming back to check out updated posts. Rich crow // Muebles Valencia
You did a great job
You did a really swell job on writing this here article.
computer disposal
Widget app
This is a great app. How about if you make one for the iPhone instead of just the Android?
You're nuts
Nice stuff. I would also suggest to do a google search for someone like Ben Tresnat for some interesting stuff on the same subject. All in all, nice job =)
Amazingly insightful article.
Amazingly insightful article. If only it was as easy to implement some of the solutions as it was to read and nod my head at each of your points :P Derek Fisher // Kreditkarte
That is genuinely helpful. I
That is genuinely helpful. I would like to ask if it would be Okay if I mentioned some of that on my own blog. Of course I would credit you and link back here also.
descalcificador de agua
Please keep on posting such
Please keep on posting such quality articles as this is a rare thing to find these days. I am always searching online for articles that can help me. Looking forward to another great blog. Good luck to the author! all the best!
Free Beats
I dont think Ive seen all the
I dont think Ive seen all the angles of this subject the way youve pointed them out. Youre a true star a rock star man. Youve got so much to say and know so much about the subject that I think you should just teach a class about it Jason Schofield // Fahrzeugbeschriftung
Best Article what i found
I'm the same way I do my best to remain neutral. It's hard if you communicate with the person the other person dislikes then you fall out of favor with them! I simple can't dislike a person just because someone else does I just can't // Tablet Android Honeycomb Terbaik Murah
This is such a great resource
This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It's the old what goes around comes around routine. John Patrick // Elektro Rasentraktor
Thanks for the post and
Thanks for the post and information! I think education is important for us so we must prepare the best education for our generation by sharing such great information with eachother! Ben Kennedy // marketing & advertising firm in Miami
This is such an informative
This is such an informative article and very clearly written. Every single thought and idea is direct to the point. Perfectly laid out. Thank you for taking your time sharing this to you readers. Phil Hammond // wedding photographers in miami
The post was able to express
The post was able to express what it wants to convey to the readers. It has been a very effective approach which resulted to a profitable output for all who have been fortunate enough to come across it! Simon Green // Mississauga air repair
This is such an informative
This is such an informative article and very clearly written. Every single thought and idea is direct to the point. Perfectly laid out. Thank you for taking your time sharing this to you readers.
driving instructor in cannock
Gloriously expert position. I
Gloriously expert position. I merely bumbled upon your post and desired to articulate that I have really relished understanding your blog articles. Cyril Brown // euromilliones
The colour schemes are lovely
The colour schemes are lovely you have made this page very attractive. But I did not like the stuff too much you really need to improve on it. Dave Daniels // video production cardiff
Great post and now I know
Great post and now I know what to do thank you! Actually this Blog post helped me a lot. I hope you continue writing about this kind of entry.
Online-Marketing
This is a great inspiring
This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.
psicologo rivas
Happy to see your blog as it
Happy to see your blog as it is just what I’ve looking for and excited to read all the posts. I am looking forward to another great article from you. Tom Williams // Arbeitslosenkredit
Happy to see your blog as it
Happy to see your blog as it is just what I’ve looking for and excited to read all the posts. I am looking forward to another great article from you. Tom Williams // Arbeitslosenkredit
Please support enhance this
Please support enhance this post by adding citations to reliable sources Unsourced material may well be challenged Vince Erdrich // learn spanish in granada
Thanks for the post and
Thanks for the post and information! I think education is important for us so we must prepare the best education for our generation by sharing such great information with eachother! John Walters // Spanisch lernen in Granada Spanien
Excellent post one of the few
Excellent post one of the few articles I’ve read today that said something unique! One new subscriber here :) Jane Smith // Alquiler coches Sevilla
A very good and informative
A very good and informative article indeed . It helps me a lot to enhance my knowledge, I really like the way the writer presented his views. xperia play accessories
Your blog provided us with
Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging. Paul Shaun // website developer london
This article gives the light
This article gives the light in which we can observe the reality. this is very nice one and gives in-depth information. thanks for this nice article... Mercedes-Benz Mobil Mewah Terbaik Indonesia | Mercedes-Benz Mobil Mewah Terbaik Indonesia | Meriahkan pesta ulang tahun bersama GarudaFood | Mari Berkomunitas Di Faceblog | Harga Jual Blackberry iPhone Laptop Murah | Video Music | Mp3 | Beauty and Health
That is some inspirational
That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here. Simon Paul // cirurgia plastica em BH
Thanks for posting this
Thanks for posting this informative article. I haven't any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. Jim Adams // Handy Forum
I'm the same way I do my best
I'm the same way I do my best to remain neutral. It's hard if you communicate with the person the other person dislikes then you fall out of favor with them! I simple can't dislike a person just because someone else does I just can't. Scott Parsons // outsourcing de impressao
Property Investment
It is nice to find a site about my interest. My first visit to your site is been a big help. Thank you for the efforts you been putting on making your site such an interesting and informative place to browse through. I'll be visiting your site again to gather some more valuable information. You truly did a good job. Property Investment
A very informative article
A very informative article and lots of really honest and forthright comments made! This certainly got me thinking a lot about this issue so thanks a lot for posting! Andy Whitaker // wedding entertainment
Lots of popular smartphones
Lots of popular smartphones use the Android operating system. As a result, consumers are clamoring for new Android apps.
best android apps
best iphone apps