我有这个小部件,它以秒或分钟的间隔更新。
将小部件添加到屏幕 PreferencesActivity 启动后,当用户决定一切都已正确设置时,他退出设置并且我正在调用方法:
public class MyWidgetConfiguration extends PreferenceActivity {
// [...] Some code...
private void createWidget() {
Context c = getApplicationContext() ;
SharedPreferences sp = getSharedPreferences( PREF_NAME+widgetID, MODE_PRIVATE );
// Set layout
AppWidgetManager awm = AppWidgetManager.getInstance( c );
RemoteViews rv = new RemoteViews( c.getPackageName(), LAYOUT_ID );
awm.updateAppWidget( widgetID, rv );
// start alarm manager running this particular widget
Intent i = new Intent( c, MyWidgetReceiver.class );
PendingIntent pi = PendingIntent.getBroadcast( c, 0, i, 0 );
AlarmManager a = (AlarmManager) c.getSystemService( Context.ALARM_SERVICE );
/**
* MY GUESS IS, THAT I'D HAVE TO ADD SOME KIND OF PendingIntent CALL HERE,
* I TRIED COUPLE OF THINGS, BUT MOST OF THEM INTERFERED OR CANCELLED FOLLOWING
* AlarmManager REPEATING...
*
* DELAY contains time left to closest full minute
*/
a.setRepeating( AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + DELAY, MINUTE, pi );
/// return widget ID
Intent resultValue = new Intent();
resultValue.putExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID );
setResult( RESULT_OK, resultValue );
finish();
}
// [...] More of some code...
}
所以,正如你在上面看到的,我从第一分钟开始每分钟调用一次 alarmManager,延迟过去后一切正常,但在此之前我的小部件有点冻结了一段时间。我想防止这种情况发生,但不向 Receiver 添加任何额外的逻辑,因为它甚至可以每秒调用一次。完整和原始代码在这里:http: //goo.gl/uOP9P