In former exercise, "A dummy Android Home Screen App Widget" without any function have been implemented. Here, we add some code in the onUpdate() method to get and show the date/time on home screen in 30 minutes interval.
Bascically the structure is same as the exercise of "Create a dummy Android Home Screen App Widget".
Modify android:updatePeriodMillis to "1800000" in /res/xml/hellowidgetproviderinfo.xml. Because "updatePeriodMillis will not be delivered more than once every 30 minutes".
Modify /res/layout/hellowidget_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/widgettext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
/>
</LinearLayout>
Modify HelloWidgetProvider.java to override methods onDeleted(), onDisabled(), onEnabled(), and mainly in onUpdate().
package com.exercise.HelloWidget;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.widget.RemoteViews;
import android.widget.Toast;
public class HelloWidgetProvider extends AppWidgetProvider {
private SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm:ss a");
String strWidgetText = "";
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
//super.onDeleted(context, appWidgetIds);
Toast.makeText(context, "onDeleted()", Toast.LENGTH_LONG).show();
}
@Override
public void onDisabled(Context context) {
// TODO Auto-generated method stub
//super.onDisabled(context);
Toast.makeText(context, "onDisabled()", Toast.LENGTH_LONG).show();
}
@Override
public void onEnabled(Context context) {
// TODO Auto-generated method stub
//super.onEnabled(context);
Toast.makeText(context, "onEnabled()", Toast.LENGTH_LONG).show();
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
String currentTime = formatter.format(new Date());
strWidgetText = strWidgetText + "\n" + currentTime;
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.hellowidget_layout);
updateViews.setTextViewText(R.id.widgettext, strWidgetText);
appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
super.onUpdate(context, appWidgetManager, appWidgetIds);
Toast.makeText(context, "onUpdate()", Toast.LENGTH_LONG).show();
}
}
CORRECTION@2011-04-03: The following statement should be moved to the first inside onUpdate() method.super.onUpdate(context, appWidgetManager, appWidgetIds);
Download the files.
next: A simple Home Screen App Widget with configure activity
Related Article:
- Home Screen Battery Widget