在自定义通知中,点击按钮执行操作:Android

4

我正在尝试在Android上自定义通知的按钮点击时执行一些操作,例如暂停音乐或播放音乐。

目前我是使用以下方式实现:

    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, "Custom Notification", when);

    NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.layout);
    contentView.setTextViewText(R.id.textView1, "Custom notification");
    contentView.setOnClickPendingIntent(R.id.button1, pIntent);
    notification.contentView = contentView;

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.contentIntent = contentIntent;

    notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
    notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
    notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
    notification.defaults |= Notification.DEFAULT_SOUND; // Sound

    mNotificationManager.notify(1, notification);

但是这个通知会带我进入另一个活动界面。 有没有办法在同一个活动中实现通知操作。

例如,我发送一个通知,用户点击它时,它不会跳转到其他活动界面,而是调用当前活动/服务中的一般方法。


我已经在给定的链接https://dev59.com/NGgu5IYBdhLWcg3wgnVh#11271367上回答了同样的问题。 - Daud Arfin
1个回答

12
首先为您的按钮分配一个意图:
    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.player_notify_layout);
    Intent buttonsIntent = new Intent(context, NotifyActivityHandler.class);
    buttonsIntent.putExtra("do_action", "play");
    contentView.setOnClickPendingIntent(R.id.imgPlayPause, PendingIntent.getActivity(context, 0, buttonsIntent, 0));

然后创建一个活动来处理每个通过通知发生的操作:
    public class NotifyActivityHandler extends Activity {
           public static final String PERFORM_NOTIFICATION_BUTTON = "perform_notification_button";
           
           @Override
           protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);

               String action = (String) getIntent().getExtras().get("do_action");
               if (action != null) {
                   if (action.equals("play")) {
                       // for example play a music
                   } else if (action.equals("close")) {
                       // close current notification
                   }
               }

               finish();
         }
    }

最后,您需要在 AndroidManifest.xml 中定义活动。此外,您可以查看此link


我实现了这个解决方案,但 setOnClickPendingIntent 对我不起作用,有什么解决办法吗? - AndyN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接