Music player control in notification

后端 未结 1 1776
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 22:20

how to set notification with play/pause, next and previous button in android.!

I am new with Android & also at stack overflow. So please bear with me.

相关标签:
1条回答
  • 2020-11-30 22:51

    You need to set a custom intent action, not the AudioPlayerBroadcastReceiver component class.

    Create a Intent with custom action name like this

      Intent switchIntent = new Intent("com.example.app.ACTION_PLAY");
    

    Then, register the PendingIntent Broadcast receiver

      PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 100, switchIntent, 0);
    

    Then, set a onClick for the play control , do similar custom action for other controls if required.

      notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
    

    Next,Register the custom action in AudioPlayerBroadcastReceiver like this

       <receiver android:name="com.example.app.AudioPlayerBroadcastReceiver" >
            <intent-filter>
                <action android:name="com.example.app.ACTION_PLAY" />
            </intent-filter>
        </receiver>
    

    Finally, when play is clicked on Notification RemoteViews layout, you will receive the play action by the BroadcastReceiver

    public class AudioPlayerBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
    
        String action = intent.getAction();
    
        if(action.equalsIgnoreCase("com.example.app.ACTION_PLAY")){
            // do your stuff to play action;
        }
       }
    }
    

    EDIT: how to set the intent filter for Broadcast receiver registered in code

    You can also set the Custom Action through Intent filter from code for the registered Broadcast receiver like this

        // instance of custom broadcast receiver
        CustomReceiver broadcastReceiver = new CustomReceiver();
    
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        // set the custom action
        intentFilter.addAction("com.example.app.ACTION_PLAY");
        // register the receiver
        registerReceiver(broadcastReceiver, intentFilter); 
    
    0 讨论(0)
提交回复
热议问题