2013-09-30 80 views
4

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

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

例如..比方說,我養notifcation,並在其上的用戶按,然後而不是帶我去一些活動,它在我的當前活動/服務

+0

我已經給了一個答案對同一給定鏈路上http://stackoverflow.com/questions/11270898/how-to-execute-a-method-by-clicking-a-notification/11271367#11271367 –

回答

10

首先是調用一些常規的避孕方法一個意圖分配給您的按鈕:

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

我希望這對你有幫助。

+0

我實現這個解決方案,但setOnClickPendingIntent不適合我,有沒有解決方案? – AndyN

相關問題