单击侦听器上的通知RemoteView

时间:2014-08-24 18:50:25

标签: android android-service android-pendingintent android-remoteview

所以,经过大量的搔痒,我在我的智慧结束。我的通知中有一个媒体播放器RemoteViews,我希望能够访问播放,暂停,上一个和下一个按钮。

我知道setOnClickPendingIntent()将用于通知通知。但是,我想知道它是如何工作的。

是否可以让服务处理点击?

我试过这个,但是徒劳无功。我试图让我服务处理暂停和恢复播放器:

rm = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notif_media_player);

        Intent intent = new Intent(getApplicationContext(), MusicService.class);
        intent.putExtra(REQUEST_CODE, PAUSE);
        PendingIntent pending = PendingIntent.getService(getApplicationContext(), PAUSE, intent, 0);
        rm.setPendingIntentTemplate(R.id.pause, pending);

        Notification notif =  new NotificationCompat.Builder(getApplicationContext())
                                 .setOngoing(true)
                                 .setSmallIcon(R.drawable.ic_launcher)
                                 .setContent(rm)
                                 .build();

        NotificationManager mgr = (NotificationManager) getApplicationContext()
                                  .getSystemService(Context.NOTIFICATION_SERVICE);
        mgr.notify(NOTIFICATION_ID, notif);  

我的IBinder为空。如果这有所作为。

如何从通知中暂停和播放音乐?

1 个答案:

答案 0 :(得分:9)

根据CommonsWare的建议:

        rm = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notif_media_player);
        Intent pauseIntent = new Intent(getApplicationContext(), MusicService.class);
        Intent dismissIntent = new Intent(getApplicationContext(), MusicService.class);

        pauseIntent.putExtra(REQUEST_CODE, PAUSE);
        dismissIntent.putExtra(REQUEST_CODE, DISMISS);

        PendingIntent pause = PendingIntent.getService(getApplicationContext(), PAUSE, pauseIntent, 0);
        PendingIntent dismiss = PendingIntent.getService(getApplicationContext(), DISMISS, dismissIntent, 0);

        rm.setOnClickPendingIntent(R.id.pause, pause);
        rm.setOnClickPendingIntent(R.id.dismiss, dismiss);

        Notification notif =  new NotificationCompat.Builder(getApplicationContext())
                                 .setOngoing(true)
                                 .setSmallIcon(R.drawable.ic_launcher)
                                 .setContent(rm)
                                 .build();

        NotificationManager mgr = (NotificationManager) getApplicationContext()
                                  .getSystemService(Context.NOTIFICATION_SERVICE);
        mgr.notify(NOTIFICATION_ID, notif);