Android怎样实现控制第三方音乐播放器暂停、播放

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Evahuangchen/article/details/53321670

1.需求

怎么控制第三方音乐播放器暂停 播放呢 

2.解决思路

写一个服务,当第三方播放器打开时 ,开启这个服务,音乐暂停;关闭服务,音乐继续

3.开启和关闭服务

startService(new Intent(MainActivity.this,StartService.class));
stopService(new Intent(MainActivity.this,StartService.class));

4.具体服务类

private AudioManager mAm;
	private static boolean vIsActive=false;
	private MyOnAudioFocusChangeListener mListener;	
	public class MyOnAudioFocusChangeListener implements OnAudioFocusChangeListener {
		@Override
		public void onAudioFocusChange(int focusChange) {
			// TODO Auto-generated method stub			
		}
	}
public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onStartCommand");
		Toast.makeText(getApplicationContext(), "服务已启动", 0).show();
		
		mAm = (AudioManager) getApplicationContext().getSystemService(
				Context.AUDIO_SERVICE);
		vIsActive=mAm.isMusicActive();
		mListener = new MyOnAudioFocusChangeListener();
		if(vIsActive)
		{
			int result = mAm.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);
	}

@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(vIsActive)
		{
			mAm.abandonAudioFocus(mListener);
		}
		Log.d(TAG, "onDestroy");
	}




展开阅读全文

没有更多推荐了,返回首页