我创建了一个带有按钮的小部件,并且在按下按钮时有一个待定的意图来打开活动。我需要知道是否可以通过某种方式重复一段时间后自动触发待处理的意图,以检查该活动中是否有更新。我需要使用AlarmManager吗?
public class MainActivity extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, But1.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
views.setOnClickPendingIntent(R.id.button1, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
最佳答案
一个简单的模式是使用广播接收器。您的服务或提供者通过以下方式发送广播:
getContext().sendBroadcast(new Intent(MyWidgetService.ACTION_UPDATE, null));
在您的窗口小部件提供程序类中实现onReceive,如下所示:
@Override
public void onReceive(Context context, Intent intent) {
if (MyWidgetService.ACTION_UPDATE.equals(intent.getAction())) {
// Do something.
// For example you can just call your widget provider's onUpdate method here.
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
assert appWidgetManager != null;
final int[] allWidgetIds;
if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
allWidgetIds = new int[] {
intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID),
};
} else {
final ComponentName componentName = new ComponentName(context, this.getClass());
allWidgetIds = appWidgetManager.getAppWidgetIds(componentName);
}
if (allWidgetIds == null || allWidgetIds.length <= 0) {
return;
}
onUpdate(context, appWidgetManager, allWidgetIds);
} else {
super.onReceive(context, intent);
}
}