我有一个在安卓系统下运行的小部件,我希望当用户点击小部件上的按钮时它可以自动更新。
但是,在我安装了小部件之后,无论用户点击哪个按钮,onReceive方法都从未被调用过。
我在我的AppWidgetProvider类中有一个如下所示的onUpdate方法:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i = 0; i < appWidgetIds.length; ++i) {
final RemoteViews rv =
new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);
final Intent nextIntent =
new Intent(context, TestAppWidgetProvider.class);
nextIntent.setAction(TestAppWidgetProvider.NEXT_ACTION);
nextIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
final PendingIntent refreshPendingIntent =
PendingIntent.getBroadcast(context, 0,
nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.next, refreshPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
然后在我的onReceive方法中,我有一个类似以下的方法:
@Override
public void onReceive(Context ctx, Intent intent) {
super.onReceive(ctx, intent);
final String action = intent.getAction();
if (action.equals(PREV_ACTION)) {
Toast.makeText(ctx, "Previous clicked..", Toast.LENGTH_SHORT).show();
} else if (action.equals(NEXT_ACTION)) {
Toast.makeText(ctx, "Next was clicked..", Toast.LENGTH_SHORT)
.show();
}
else {
Toast.makeText(ctx, "Other action..", Toast.LENGTH_SHORT).show();
}
}
我也在我的清单文件中添加了这个:
<receiver android:name="com.test.android.widget.TestAppWidgetProvider" >
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<intent-filter >
<action android:name="com.test.android.widget.PREV" />
</intent-filter>
<intent-filter >
<action android:name="com.test.android.widget.NEXT" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info" />
</receiver>
安装了小部件并点击下一个按钮后,由于某种原因onReceive方法从未被调用...