当我从手机上的小部件页面添加我的小部件时,它会播放Toast消息“Button Clicked”。只有按下按钮才会显示toast,并且它可以正常工作,但是当小部件添加到屏幕时它也会显示..
我猜它可能与超级有关,但我不完全确定。
代码:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, Provider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.onoffbutton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
Toast.makeText(context, "Button Clicked", Toast.LENGTH_SHORT).show();
System.out.println("Click!");
}
}
编辑:
public static String BUTTON_CLICK = "android.appwidget.action.BUTTON_CLICK";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, Provider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
Intent clickIntent = new Intent(context, Provider.class);
clickIntent.setAction(BUTTON_CLICK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.onoffbutton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent clickIntent) {
super.onReceive(context, clickIntent);
if (clickIntent.getAction().equals(BUTTON_CLICK)) {
Toast.makeText(context, "Button Clicked", Toast.LENGTH_SHORT).show();
System.out.println("Click!");
}
}
答案 0 :(得分:2)
那是因为您对小部件更新有相同的操作
为按钮单独执行意图操作(例如BTN_ACTION)。在onReceive()中检查i = action intent有哪些,如果是intent.getAction()。equals(BTN_ACTION) - 处理按钮点击。