I have created a widget to display the current date which refreshes every 5-10 seconds (Will be increasing the duration later). Created an alarm in the onUpdate method to create the intent for the service. Created an onReceive method extending broadcast receiver) to start the service which in turn updates the widget with the date. When I invoke the widget onReceive fires initially and displays the date. After that the alarm doesn't fire.
1) Am I right in including an onReceive method and calling startservice? 2) How do I know the create alarm is active and not firing? 3) What is wrong with the following code?
Please help.
Thanks, Sam
public class WorldCupScores extends AppWidgetProvider {
public static String TAG = "myActivity";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "receiveeeeeeeeeeee");
Toast.makeText(context, "Receiver", Toast.LENGTH_LONG).show();
context.startService(new Intent(context, UpdateService.class));
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// To prevent any ANR timeouts, we perform the update in a service
//context.startService(new Intent(context, UpdateService.class));
AlarmManager alarmManager;
Log.d(TAG, "before intenttttt");
Intent intent = new Intent(context, UpdateService.class);
Log.d(TAG, "afterrrr intenttttt");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, 0);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5*1000, pendingIntent);
Toast.makeText(context, "My alarm started", Toast.LENGTH_LONG).show();
Log.d(TAG, "alarmmmmmmmm");
}
public static class UpdateService extends Service {
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "Inside Serviceeeeeeeeeeeeeeeeeeeee");
// Build the widget update for today
//RemoteViews updateViews = buildUpdate(this);
RemoteViews updateViews = new RemoteViews(this.getPackageName(),
R.layout.main);
Date date = new Date();
updateViews.setTextViewText(R.id.scores, "Current Time "
+ date);
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(this, WorldCupScores.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, updateViews);
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
// We don't need to bind to this service
return null;
}
}
}
I wouldn't quite do it that way. In your current code,
onUpdate()
will never be called, becauseonReceive()
never chains to the superclass.If it is not firing, it is not active. And, since
onUpdate()
is not being called, your alarm is never being scheduled.