实现控制第三方音乐播放器思路:
1.参考方法:可能实现第三方音乐播放器暂停/播放/下一曲/上一曲
思路:android模拟发送键值,就像蓝牙耳机等远程设备切换歌曲操作,但是行不通。原因是现在Android系统中,InputManager中的injectInputEvent方法有/*@hide/标记,个人建议做产品,为了安全起见,还是不要费大力气用这个方法了。
这是以前见到过的做法:
import android.hardware.input.InputManager;
/**
* 通过模拟KeyEvent触控事件来控制媒体音乐的播放
*/
private long mKeyRemappingSendFakeKeyDownTime;
private void keyRemappingSendFakeKeyEvent(int action, int keyCode) {
long eventTime = SystemClock.uptimeMillis();
if (action == KeyEvent.ACTION_DOWN) {
mKeyRemappingSendFakeKeyDownTime = eventTime;
}
KeyEvent keyEvent = new KeyEvent(mKeyRemappingSendFakeKeyDownTime, eventTime, action, keyCode, 0);
InputManager inputManager = (InputManager) mContext.getSystemService(Context.INPUT_SERVICE);
inputManager.injectInputEvent(keyEvent, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
}
2.验证过方法:能够实现第三方音乐播放器暂停/播放功能
思路:写一个服务,当第三方播放器打开时 ,开启这个服务,音乐暂停;关闭服务,音乐继续
// 实现原理:打开服务,第三方音乐暂停;关闭服务,第三音乐继续播放
// 关闭音乐播放服务
stopService(new Intent(MainActivity.this,MusicService.class));
// 开启音乐播放服务
startService(new Intent(MainActivity.this,MusicService.class));
音乐服务工具类:
public class MusicService extends Service {
private final String TAG = "MusicService";
/**
* 音频管理类
*/
private AudioManager mAudioManager;
/**
* 是否播放音乐
*/
private static boolean vIsActive=false;
/**
* 音乐监听器
*/
private MyOnAudioFocusChangeListener mListener;
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
// 获取系统音乐服务
mAudioManager = (AudioManager) getApplicationContext().getSystemService(
Context.AUDIO_SERVICE);
// 获取系统音乐服务状态
vIsActive=mAudioManager.isMusicActive();
mListener = new MyOnAudioFocusChangeListener();
if(vIsActive) {//播放状态
int result = mAudioManager.requestAudioFocus(mListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
Log.d(TAG, "requestAudioFocus successfully.");
}
else
{
Log.d(TAG, "requestAudioFocus failed.");
}
}
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(vIsActive)
{
mAudioManager.abandonAudioFocus(mListener);
}
Log.d(TAG, "onDestroy");
}
/**
* 内部类:音乐监听器
*/
public class MyOnAudioFocusChangeListener implements AudioManager.OnAudioFocusChangeListener {
@Override
public void onAudioFocusChange(int focusChange) {
// TODO Auto-generated method stub
}
}
}
参考https://blog.csdn.net/qq_26440221/article/details/71512648
https://blog.csdn.net/qq_25815655/article/details/82842528