private void start() {
mediaPlayer.start();
//当播放歌曲的时候,在状态显示正在播放,点击的时候,可以进入音乐播放页面
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//最主要
Intent intent = new Intent(this, AudioPlayerActivity.class);
intent.putExtra("notification",true);//标识来自状态拦
PendingIntent pendingIntent = PendingIntent.getActivity(this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.notification_music_playing)
.setContentTitle("321音乐")
.setContentText("正在播放:"+getName())
.setContentIntent(pendingIntent)
.build();
manager.notify(1, notification);
}
/**
* 播暂停音乐
*/
private void pause() {
mediaPlayer.pause();
manager.cancel(1);
}
避免从状态栏进入活动后重新播放歌曲
private void getData() {
notification = getIntent().getBooleanExtra("notification", false);
if(!notification){
position = getIntent().getIntExtra("position",0);
}
}
避免从状态栏进入活动中时重新与服务连接导致执行 service.openAudio(position);
重新进入活动中时没有intent传进来‘position’,此时的position默认为0,所以会导致从头开始播放。
private ServiceConnection con = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
service = IMusicPlayerService.Stub.asInterface(iBinder);
if (service != null) {
try {
if(!notification){//从列表
service.openAudio(position);
}else{
System.out.println("onServiceConnected==Thread-name=="+Thread.currentThread().getName());
//从状态栏
showViewData();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
if (service != null) {
try {
service.stop();
service = null;
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
};