0
與this教程我已經創建了一個帶按鈕的小部件。在下面的代碼中,當我點擊ButtonP1時,看到一個祝酒信息。我也嘗試使用ButtonP2來做同樣的事情,但是隻有一個祝酒消息被設置爲ButtonP1。我怎麼做,當用戶點擊ButtonP2時,另一個吐司味精出現?Android Widget按鈕
public class HelloWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
context.startService(new Intent(context, UpdateService.class));
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widgetmain);
Intent active = new Intent(context, HelloWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
active.putExtra("msg", "Message for Button P1");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.ButtonP1, actionPendingIntent);
Intent active2 = new Intent(context, HelloWidget.class);
active2.setAction(ACTION_WIDGET_RECEIVER);
active2.putExtra("msg", "Message for Button P2");
PendingIntent actionPendingIntent2 = PendingIntent.getBroadcast(context, 0, active2, 0);
remoteViews.setOnClickPendingIntent(R.id.ButtonP2, actionPendingIntent2);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action))
{
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID)
{
this.onDeleted(context, new int[] { appWidgetId });
}
}
else
{
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER))
{
String msg = "null";
try {
msg = intent.getStringExtra("msg");
} catch (NullPointerException e) {
Log.e("Error", "msg = null");
}
Toast.makeText(context, "Out: " + msg, Toast.LENGTH_SHORT).show();
}
super.onReceive(context, intent);
}
}
}
我曾經嘗試這樣做(ACTION_WIDGET_RECEIVER2而不是ACTION_WIDGET_RECEIVER)
Intent active2 = new Intent(context, HelloWidget.class);
active2.setAction(ACTION_WIDGET_RECEIVER2);
active2.putExtra("msg", "Message for Button P2");
PendingIntent actionPendingIntent2 = PendingIntent.getBroadcast(context, 0, active2, 0);
remoteViews.setOnClickPendingIntent(R.id.ButtonP2, actionPendingIntent2);
與
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER2))
{
String msg2 = "null";
try {
msg2 = intent.getStringExtra("msg2");
} catch (NullPointerException e) {
Log.e("Error", "msg = null");
}
Toast.makeText(context, "Out2: " + msg2, Toast.LENGTH_SHORT).show(); //null
}
後相同的,如果行
。在這種情況下,msg2變量爲空。