操作通知栏的按纽时发送广播,自定义NotificationReceiver,并静态注册,在NotificationReceiver中控制音频播放
public class NotificationReceiver extends BroadcastReceiver {
public static final String ACTION_STATUS_BAR = "com.sktcm.app.doctor.utils.audio.NOTIFICATION_ACTIONS";
public static final String EXTRA = "extra";
public static final String EXTRA_PLAY = "play_pause";
public static final String EXTRA_NEXT= "play_next";
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || TextUtils.isEmpty(intent.getAction())) {
return;
}
String extra = intent.getStringExtra(EXTRA);
if (EXTRA_PLAY.equals(extra)) {
if (AudioPlayer.getInstance().getStatus() == ManagedMediaPlayer.Status.STARTED) {
AudioPlayer.getInstance().pause();
} else if (AudioPlayer.getInstance().getStatus() == ManagedMediaPlayer.Status.PAUSED){
AudioPlayer.getInstance().resume();
}
} else if (EXTRA_NEXT.equals(extra)){
AudioPlayer.getInstance().next();
}
}
}
使用前台服务开始播放音频
public class PlayerService extends Service {
private static String ACTION_START = "ACTION_START";
private static String ACTION_PREVIOUS = "ACTION_PREVIOUS";
private static String ACTION_NEXT = "ACTION_NEXT";
private static String ACTION_GONE = "ACTION_GONE";
private static String ACTION_STOP = "ACTION_STOP";
public static void startPlayerService() {
Intent intent = new Intent(MyApplication.getContext(), PlayerService.class);
intent.setAction(ACTION_START);
MyApplication.getContext().startService(intent);
}
public static void playerPreviousService() {
Intent intent = new Intent(MyApplication.getContext(), PlayerService.class);
intent.setAction(ACTION_PREVIOUS);
MyApplication.getContext().startService(intent);
}
public static void playerNextService() {
Intent intent = new Intent(MyApplication.getContext(), PlayerService.class);
intent.setAction(ACTION_NEXT);
MyApplication.getContext().startService(intent);
}
public static void stopPlayerService() {
Intent intent = new Intent(MyApplication.getContext(), PlayerService.class);
MyApplication.getContext().stopService(intent);
}
@Override
public void onCreate() {
super.onCreate();
// 开始前台服务
Notifier.getInstance().init(this);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction() != null) {
if (ACTION_START.equals(intent.getAction())) {
AudioPlayer.getInstance().play ();
} else if (ACTION_PREVIOUS.equals(intent.getAction())) {
AudioPlayer.getInstance().previous();
} else if (ACTION_NEXT.equals(intent.getAction())) {
AudioPlayer.getInstance().next();
}
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
AudioPlayer.getInstance().release();
Notifier.getInstance().stopForeground();
}
}
传入播放列表,并开始服务即可播放
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/bofangqi/article-120690-5.html
让美彻底放弃冷战思维除非衰退加速
我词穷了T_T