我的小部件的onUpdate方法应该做两件事:
这是我的方法的样子:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
// Create an Intent to launch Activity
Intent openApp = new Intent(context, MainActivity.class);
openApp.putExtra("IntentId", 1);
PendingIntent pendingAppIntent = PendingIntent.getActivity(context, 1, openApp, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.hsvuhr_widget);
views.setOnClickPendingIntent(R.id.rlmy, pendingAppIntent);
Intent update = new Intent(context, UpdateService.class);
update.putExtra("IntentId",2);
PendingIntent pendingUpdateIntent = PendingIntent.getService(context, 2, update, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingUpdateIntent);
long interval = 10000;
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pendingUpdateIntent);
}
}
但是这段代码是个错误。 onClickListener不起作用。 Widget每10秒更新一次,但是当我点击小部件时,我什么也没有打开。
任何人都可以看到我的错误吗?
编辑:这就是我改变代码的方式。这是我的AppWidgetProvider
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Create an Intent to launch Activity
Intent openApp = new Intent(context, MainActivity.class);
openApp.putExtra("IntentId", 1);
PendingIntent pendingAppIntent = PendingIntent.getActivity(context, 1, openApp, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.hsvuhr_widget);
views.setOnClickPendingIntent(R.id.rlmy, pendingAppIntent);
Intent update = new Intent(context, UpdateService.class);
update.putExtra("IntentId",2);
PendingIntent pendingUpdateIntent = PendingIntent.getService(context, 2, update, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingUpdateIntent);
long interval = 5000;
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pendingUpdateIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
这是我的updateClass:
@Override
protected void onHandleIntent(Intent intent) {
Context context = this;
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.hsvuhr_widget);
ComponentName thisWidget = new ComponentName(context,HSVUhrWidget.class);
remoteViews.setTextViewText("stuff");
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
因此onUpdate将每5秒调用一次updateClass。 update类将触发appWidgetManager.updateAppWidget(thisWidget,remoteViews);然后,在AppWidgetProvider中会有另一个appWidgetManager.updateAppWidget(appWidgetIds,views)。
现在出现问题:窗口小部件正确更新,但在第一次更新后,onClickEvent不会触发。所以我可以先打开应用程序,但在更新后我就不能再这样做了。我的错误在哪里?
答案 0 :(得分:0)
在方法调用结束时
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);