我使用 AlarmManager 每秒更新一个小部件,但是当添加更多小部件时,仅更新最后一个小部件。我不明白为什么...
这是代码...
public class widget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
SharedPreferences preference = context.getSharedPreferences("MY_PREFERENCE", Context.MODE_PRIVATE);
Intent intent = new Intent(context,vampireServiceWidget.class);
context.startService(intent);
for(int i=0; i<appWidgetIds.length;i++){
if(preference.getLong("countdown", 0)!=0){
//Parte il countdown
Intent in = new Intent().setAction("it.android.dev.thevampirediaries.UPDATE_COUNTDOWN");
in.putExtra("id_widget", appWidgetIds[i]);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 1000, pi);
} }
}
进入广播这个代码
AppWidgetManager manager = AppWidgetManager.getInstance(context);
RemoteViews remoteView = new RemoteViews(context.getPackageName(),R.layout.widgett);
thisWidget=intent.getIntExtra("id_widget", 0)
SimpleTimeFormat tf = new SimpleTimeFormat("$dd$ : $HH$: $mm$: $ss$");
String risultato = tf.format(countdown_data_fine - new Date().getTime()); // arg0 tempo
remoteView.setTextViewText(R.id.textView1, titolo_puntata);
remoteView.setTextViewText(R.id.textView2, risultato);
manager.updateAppWidget(thisWidget, remoteView);