Music player control in notification

喜你入骨 提交于 2019-11-27 06:25:32

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); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!