1. 程式人生 > >Android的Widget的定時重新整理

Android的Widget的定時重新整理

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的操作。