Media Player controls in Notification

前端 未结 5 647
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 19:14

I have written complete Music Player to stream music from the web, but I don\'t know how to put media player controls in Notification and when the screen is Lock.

I am f

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 19:45

    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

    
        
            
        
    
    

    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); 
    

    check this link for more info

    https://www.binpress.com/tutorial/using-android-media-style-notifications-with-media-session-controls/165

提交回复
热议问题