Aug 30, 2012

Home Screen Widget step-by-step - modify our App Widget Provider (AppWidgetProvider) to update widget RemoteViews

It's part of the Home Screen Widgets step-by-step series.

Up to last post, we have a dummy home screen widget without any function. In this step, we are going to modify, override onUpdate() method to updateAppWidget() with RemoteViews.

override onUpdate() method to updateAppWidget() with RemoteViews.
package com.example.androidhomewidget;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;

public class WidgetProvider extends AppWidgetProvider {

 public void onDeleted(Context context, int[] appWidgetIds) {
  // TODO Auto-generated method stub
  super.onDeleted(context, appWidgetIds);

 public void onDisabled(Context context) {
  // TODO Auto-generated method stub

 public void onEnabled(Context context) {
  // TODO Auto-generated method stub

 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
  super.onReceive(context, intent);

 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {
  for(int i = 0; i < appWidgetIds.length; i++){
   int id = appWidgetIds[i];
     "onUpdate: " + String.valueOf(id), 
   RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
   remoteViews.setTextViewText(, String.valueOf(id));
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");
   String now = simpleDateFormat.format(new Date());
   remoteViews.setTextViewText(, now);
   appWidgetManager.updateAppWidget(id, remoteViews);
   super.onUpdate(context, appWidgetManager, appWidgetIds);


Refer to our app widget provider, onUpdate() will be call every 30 minutes (1800000 millisecond). It's a approximated reference, no guarantee how accurate is it.

No comments:

Post a Comment

Infolinks In Text Ads