我通过在 onUpdate 中向 Intent 添加一个操作然后对 onReceive 进行 if 检查以查看是否单击了小部件,从而解决了这个问题:
我添加intentClick.setAction(WIDGET_CLICKED);
了仅在单击小部件时触发的内容。
public class WidgetProvider extends AppWidgetProvider {
private static final String TAG = WidgetProvider.class.getSimpleName();
private static String WIDGET_CLICKED = "widget_clicked";
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.e(TAG, "onUpdate()");
remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
watchWidget = new ComponentName(context, WidgetProvider.class);
Intent intentClick = new Intent(context, WidgetProvider.class);
intentClick.setAction(WIDGET_CLICKED);
intentClick.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, "" + appWidgetIds[0]);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetIds[0], intentClick, 0);
remoteViews.setOnClickPendingIntent(R.id.img_btn, pendingIntent);
remoteViews.setInt(R.id.img_btn, "setBackgroundResource", R.drawable.play);
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.e(TAG, "onReceive()");
Bundle extras = intent.getExtras();
//If AND ONLY IF WIDGET_CLICKED
if (extras != null && intent.getAction().equals(WIDGET_CLICKED)) {
remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
//If isPlaying
if (isPlaying) {
//setBackground as PLAY
remoteViews.setInt(R.id.img_btn, "setBackgroundResource", R.drawable.play);
isPlaying = false;
Intent i = new Intent(context, MediaPlayerService.class);
i.putExtra("command", "stopSong");
context.startService(i);
//If NOT playing
} else {
//setBackground as STOP
remoteViews.setInt(R.id.img_btn, "setBackgroundResource", R.drawable.stop);
isPlaying = true;
Intent i = new Intent(context, MediaPlayerService.class);
i.putExtra("command", "playRandomSong");
context.startService(i);
}
watchWidget = new ComponentName(context, WidgetProvider.class);
(AppWidgetManager.getInstance(context)).updateAppWidget(watchWidget, remoteViews);
}
}