【问题标题】:Perform Action On Button Click in Custom Notification : Android在自定义通知中执行按钮单击操作:Android
【发布时间】:2013-09-30 11:01:14
【问题描述】:

我正在尝试执行一些操作,例如暂停音乐,在 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);

但是这个带我去另一个活动。 无论如何要对同一活动实施通知操作。

例如..假设我提出了一个通知,当用户按下它时,它不会带我去一些活动,而是在我当前的活动/服务中调用一些常规方法

【问题讨论】:

标签: android onclick android-notifications


【解决方案1】:

首先为您的按钮分配一个意图:

    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 对我不起作用,有什么解决方案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
相关资源
最近更新 更多