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
-
@Idevicegazette (iDevice Gazette)
GSM-to-Skype bridge lets you lose those roaming fees http://bit.ly/lbRJeh #android
11 years 46 weeks ago -
@tommy_banane (tom b.)
RT @AndroidFavorite: #Android New Desktop Android Market Is Live, Adds Several New Features http://zorr0.nl/lFwXNz
11 years 46 weeks ago -
@dwilliams5 (Dennis Williams)
just completed a runtastic run of 3.02 km in 40 min 11 s with #runtastic #Android App: http://tinyurl.com/5tvrpe3
11 years 46 weeks ago -
@S_Pinz (Spinz!)
RT @Androidheadline: Out of box #LG Optimus 3D got Quadrant 2420 score. Thanks @blink_c #io2011 #android http://twitpic.com/4whkdz
11 years 46 weeks ago -
@tayaitapps (Taya IT)
Next Google TV Looks A Lot Like Android http://t.co/dvlTim3 via @alleyinsider #google #apple #android #tv #honeycomb
11 years 46 weeks ago
Poll
Useful resources
Android Development Projects
- Bus Tracker App -- 2
- fix a flutter code
- Find a expert for setting flutter environment.
- I nedd a satta/matka application.
- Looking for full stack web and mobile developer
- Linx Project
- Satta/Matka app with admin panel.
- Educational Application
- Flutter ios build and upload to app store -- 2
- Website dan aplikasi