触发不同的每个通知按钮被点击

问题描述:

我正在创建一个媒体通知,需要根据点击按钮触发不同的功能。是否有任何方法来区分按钮或我是否需要创建4-5个独立的Intents和PendingIntents?这里是代码的作品,但不是如何应该如何:触发不同的每个通知按钮被点击

编辑:我添加了一个新的函数,初始化新的待定意图,但这里是事情,当我按play playIntent被触发,但当我按暂停意图playIntent正在被再次触发。

private void showNotification(boolean persistent) { 
     String channel_id = "TEST_CHANNEL"; 
     NotificationManager manager = (NotificationManager) getSystemService(
       Context.NOTIFICATION_SERVICE 
     ); 

     if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { 
      NotificationChannel testChannel = new NotificationChannel(
        channel_id, 
        "TEST_CHANNEL", 
        NotificationManager.IMPORTANCE_DEFAULT 
      ); 

      testChannel.setLightColor(Color.GREEN); 

      assert manager != null; 
      manager.createNotificationChannel(testChannel); 
     } 


     PendingIntent pauseIntent = initIntent("pause"); 
     PendingIntent playIntent = initIntent("play"); 

     NotificationCompat.Builder mBuilder = 
       new NotificationCompat.Builder(this, channel_id) 
         .setSmallIcon(R.drawable.ic_remote_control) 
         .addAction(R.drawable.ic_play_button, "Play", playIntent) 
         .addAction(R.drawable.ic_round_pause_button, "Pause", pauseIntent) 
         .addAction(R.drawable.ic_forward, "Title", null) 
         .addAction(R.drawable.ic_back_left_arrow_circular_button, "Title", null) 
         .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()) 
         .setOngoing(persistent) 
         .setAutoCancel(true); 


     assert manager != null; 
     manager.notify(123, mBuilder.build()); 
    } 

    private PendingIntent initIntent(String action) { 
     Intent tempIntent = new Intent(this, ActionReceiver.class); 

     tempIntent.putExtra("action", action); 

     TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 

     stackBuilder.addNextIntent(tempIntent); 


     return PendingIntent.getBroadcast(
       this, 
       1, 
       tempIntent, 
       PendingIntent.FLAG_UPDATE_CURRENT 
     ); 
    } 

您需要为每个操作创建不同的待定意图。尽管如此,您可以使用相同的类来处理基于每个待定意图的不同操作的所有操作。

+0

请检查最新的代码,我做到了,但它仍然不起作用 – Nick

+0

请粘贴您的ActionReceiver类。在ActionReceiver中,您可以根据“操作”操作字符串进行区分 – nomag