Android的桌面小图标Widget有时候需要定时的刷新,而且updatePeriodMillis属性设置的时间是建议是1个小时。这个时间对有些功能就太长时间了。在开发者文档上面有建议用AlarmManager
下面就是我写的一个小的Demo,让Widget上的ProgressBar以一秒钟progress增加一的速度更新。
在onEnable中开一个定时器每秒唤醒WidgetUpdateReceiver一次做一次页面刷新。并且在onDisabled中将它取消。
@Override public void onEnabled(Context context) { // Intent service = new Intent(context,WidgetUpdateService.class); // context.startService(service); long firstTime = SystemClock.elapsedRealtime(); firstTime += 1000; Intent receiver = new Intent(); receiver.putExtra("FirstTime",firstTime); receiver.setAction(WidgetUpdateReceiver.ACTION); PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 2006, receiver, 0); AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, 1000, pendingIntent); Log.i(TAG, "onEnabled: "); super.onEnabled(context); }
@Override public void onDisabled(Context context) { // Intent service = new Intent(context,WidgetUpdateService.class); // context.stopService(service); Intent intent = new Intent(); intent.setAction(WidgetUpdateReceiver.ACTION); PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(),2006,intent,0); AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); am.cancel(pendingIntent); Log.i(TAG, "onDisabled: "); super.onDisabled(context); }
public class WidgetUpdateReceiver extends BroadcastReceiver {
public static String TAG = "WidgetUpdateReceiver";
public static final String ACTION = "android.appwidget.action.PROGRESS_UPDATE";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive: ");
// receiver.putExtra("FirstTime",firstTime);
long currentTime = SystemClock.elapsedRealtime();
long firstTime = intent.getLongExtra("FirstTime", SystemClock.elapsedRealtime());
int progress = (int)(currentTime-firstTime)/1000;
if (progress > 100){
Toast.makeText(context,"progress到100了",Toast.LENGTH_SHORT).show();
progress = 100;
}
AppWidgetManager am = AppWidgetManager.getInstance(context);
//Widget是在其他应用上面显示的所以要用RemoteViews来管理
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.my_widget);
Intent i = new Intent(context,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,2016,i,0);
//设置点击图片的点击事件,打开一个Activity
remoteViews.setOnClickPendingIntent(R.id.iv, pendingIntent);
remoteViews.setProgressBar(R.id.progressBar,100,progress,false);
ComponentName name = new ComponentName(context,MyWidget.class);
am.updateAppWidget(name,remoteViews);
}
}
在这个Receiver中就可以做一些刷新Widget的操作。