首页 养生问答 疾病百科 养生资讯 女性养生 男性养生

Android怎样实现控制系统音乐播放器暂停

发布网友 发布时间:2022-04-20 08:12

我来回答

1个回答

热心网友 时间:2022-04-20 01:42

当music在播放音乐时,进入app时,音乐暂停;退出app后,继续播放音乐;music没有播放音乐时,进入app和退出app,不会播放音乐。
具体实现如下:
1.在MainActivity.java
private static boolean flagMusic;
private AudioManager vAudioManager=null;
在onCreate方法里初始化
vAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
boolean vIsActive = vAudioManager.isMusicActive();
if (vIsActive) {
              Toast.makeText(getApplicationContext(), "有音乐在播放", Toast.LENGTH_SHORT).show();
flagMusic = true;//记录音乐播放状态 true为正在播放 ,反之
pauseMusic();//暂停音乐播放
} else {
             Toast.makeText(getApplicationContext(), "没有音乐在播放", Toast.LENGTH_SHORT).show();
flagMusic = false;
}
2.自定义暂停和继续播放方法
private void pauseMusic() {
Intent freshIntent = new Intent();
freshIntent.setAction("com.android.music.musicservicecommand.pause");
freshIntent.putExtra("command", "pause");
sendBroadcast(freshIntent);
}
private void continuMusic() {
Intent freshIntent = new Intent();
         freshIntent.setAction("com.android.music.musicservicecommand.togglepause");
freshIntent.putExtra("command", "togglepause");
sendBroadcast(freshIntent);
}
3.在onDestroy方法
@Override
protected void onDestroy() {
// TODO Auto-generated method stub   
                if (flagMusic) {
continuMusic();//继续播放
}
super.onDestroy();
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com