簡體   English   中英

按鈕執行操作單擊自定義通知:Android

[英]Perform Action On Button Click in Custom Notification : Android

我正在嘗試執行一些動作,如暫停音樂,在按鈕點擊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);

但是這個帶我去另一個活動。 無論如何都要對同一活動實施通知操作。

例如..讓我說我提出了一個通知,當用戶按下它時,然后在我當前的活動/服務中調用一些常規方法而不是帶我去做某些活動

首先為您的按鈕分配一個意圖:

    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中定義活動。 您也可以查看此鏈接

我希望這對你有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM