我有一个MediaPlayerService,当前单击ListView项目上的播放/暂停按钮时启动。请参阅下面的代码(CustomListAdapter):
Intent intent = new Intent(v.getContext(),MediaPlayerService.class);
intent.putExtra("StreamLink",audio);
activity.startService(intent);
当上述代码启动此服务时,我想创建一个带有播放/停止按钮的通知。用户应该能够退出应用,能够停止媒体播放,例如player.stop()并启动player.start()。此外,当单击通知时,它应该将用户返回到MainActivity。
我的MediaPlayerService.java的代码:
public class MediaPlayerService extends Service implements MediaPlayer.OnPreparedListener {
MediaPlayer mMediaPlayer = null;
public String audioStreamLink;
public int onStartCommand(Intent intent, int flags, int startId) {
// Get the Audio Streaming Link from the parsed JSON in the Main Activity
audioStreamLink = intent.getStringExtra("StreamLink");
// Instantiate MediaPlayer, set the Audio Type and acquire a wakelock, set the Media Player Data Source and Prepare.
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mMediaPlayer.setDataSource(audioStreamLink);
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/** Called when MediaPlayer is ready */
@Override
public void onPrepared(MediaPlayer player) {
player.start();
}
@Override
public void onDestroy() {
mMediaPlayer.stop();
mMediaPlayer.reset();
if (mMediaPlayer != null) mMediaPlayer.release();
}
}
答案 0 :(得分:0)
获取通知的过程完全记录在文档中,例如see this。
为了帮助您完成所有这些大文档,这些是要点:
NotificationCompat.Builder
startForeground()
addAction()
向通知添加可点击按钮。PendingIntent
定义,在回复时,它是一种正常的Intent
。onStartCommand()
(如果正确配置了意图)。action
,以便您可以在收到意图时识别意图。onStartCommand()
内,您可以根据此意图行动播放/暂停并执行其他操作。我建议你阅读一些参考文献:
如果您使用MediaSession
播放媒体,情况会有所不同。