最近看了有关AppWidget的文档,对以前做的音乐播放器进行了修改,增加了Widget功能。效果如下:
写了Widget类,继承了AppWidgetProvider,重写了onUpdate方法,如下:
- @Override
- public void onUpdate(Context context, AppWidgetManager appWidgetManager,
- int[] appWidgetIds) {
- //
- RemoteViews views=new RemoteViews(context.getPackageName(), R.layout.widget_layout);
- Intent upIntent=new Intent(context, MyPlayService.class);
- upIntent.putExtra("command", Command.UP);
- Intent startIntent=new Intent(context, MyPlayService.class);
- startIntent.putExtra("command", Command.START);
- Intent pauseIntent=new Intent(context, MyPlayService.class);
- pauseIntent.putExtra("command", Command.PAUSE);
- Intent stopIntent=new Intent(context, MyPlayService.class);
- stopIntent.putExtra("command", Command.STOP);
- Intent nextIntent=new Intent(context, MyPlayService.class);
- nextIntent.putExtra("command", Command.NEXT);
- Log.i(TAG, "---Intent's content---");
- Log.i(TAG, "upIntent--->"+upIntent);
- Log.i(TAG, "startIntent--->"+startIntent);
- Log.i(TAG, "pauseIntent--->"+pauseIntent);
- Log.i(TAG, "stopIntent--->"+stopIntent);
- Log.i(TAG, "nextIntent--->"+nextIntent);
- PendingIntent upPending=PendingIntent.getService(context, 0, upIntent, 0);
- PendingIntent startPending=PendingIntent.getService(context, 0, startIntent, 0);
- PendingIntent pausePending=PendingIntent.getService(context, 0, pauseIntent, 0);
- PendingIntent stopPending=PendingIntent.getService(context, 0, stopIntent, 0);
- PendingIntent nextPending=PendingIntent.getService(context, 0, nextIntent, 0);
- views.setOnClickPendingIntent(R.id.btn_up, upPending);
- views.setOnClickPendingIntent(R.id.btn_start, startPending);
- views.setOnClickPendingIntent(R.id.btn_pause, pausePending);
- views.setOnClickPendingIntent(R.id.btn_stop, stopPending);
- views.setOnClickPendingIntent(R.id.btn_next, nextPending);
- for(int i=0; i<appWidgetIds.length; i++){
- appWidgetManager.updateAppWidget(appWidgetIds[i], views);
- }
- super.onUpdate(context, appWidgetManager, appWidgetIds);
- }
然后我在MyPlayService类中的onCommand方法里打印收到的command,发现无论按哪一个按钮,LogCat输出地command都是同一个值。
这和我的预期是不一样的。通过多次查找,发现问题发生在生成PendingIntent对象时,把requestCode都设为同一个值了,这就导致了上述现象。
把requestCode设为不同的值即可消除上述现象。
- PendingIntent upPending=PendingIntent.getService(context, 0, upIntent, 0);
- PendingIntent startPending=PendingIntent.getService(context, 1, startIntent, 0);
- PendingIntent pausePending=PendingIntent.getService(context, 2, pauseIntent, 0);
- PendingIntent stopPending=PendingIntent.getService(context, 3, stopIntent, 0);
- PendingIntent nextPending=PendingIntent.getService(context, 4, nextIntent, 0);