Up to last post, we have a dummy home screen widget without any function. In this step, we are going to modify WidgetProvider.java, override onUpdate() method to updateAppWidget() with RemoteViews.
WidgetProvider.java
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 {
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onDeleted(context, appWidgetIds);
}
@Override
public void onDisabled(Context context) {
// TODO Auto-generated method stub
super.onDisabled(context);
}
@Override
public void onEnabled(Context context) {
// TODO Auto-generated method stub
super.onEnabled(context);
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for(int i = 0; i < appWidgetIds.length; i++){
int id = appWidgetIds[i];
Toast.makeText(context,
"onUpdate: " + String.valueOf(id),
Toast.LENGTH_LONG).show();
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.widget_id, String.valueOf(id));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");
String now = simpleDateFormat.format(new Date());
remoteViews.setTextViewText(R.id.widget_status, 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.
0 Response to "Home Screen Widget step-by-step - modify our App Widget Provider (AppWidgetProvider) to update widget RemoteViews"
Posting Komentar