android 耳机按钮控制音乐播放
Posted 踏雪羽翼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 耳机按钮控制音乐播放相关的知识,希望对你有一定的参考价值。
1、一般我们耳机上有按钮可以实现音量加减控制中间还有一个按钮也可以监听到它的点击事件。还有就是可以监听到耳机的插拔事件。
2、首先实现耳机插拔事件的监听,注册一个插拔事件的静态action
<action android:name="android.media.AUDIO_BECOMING_NOISY" />
3、注册一个用于监听耳机点击事件的监听
<action android:name="android.intent.action.BOOT_COMPLETED" />
4、注册一个广播用于接受这两个事件的监听
<receiver android:name=".MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
<action android:name="android.media.AUDIO_BECOMING_NOISY" />
</intent-filter>
</receiver>
5、写一个广播接收点击事件,并实现功能,详细看注释
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
public class MediaButtonReceiver extends BroadcastReceiver
private long mFirstClickTime = 0;
private long mSecondClickTime = 0;
private static final int MSG_CLICK_DEAL = 2;
private static Context mContext;
private static int mClickNumber = 0;
private static long mSaveFirstTime = 0;
private static Handler mHandler = new Handler()
@Override
public void handleMessage(Message msg)
switch (msg.what)
case MSG_CLICK_DEAL:
if (mClickNumber == 0)
//单击的时候可以在这里实现播放和停止播放
else if (mClickNumber == 1)
//双击的时候可以上一首或着下一首
else if (mClickNumber == 2)
//三击的时候可以实现上一首或者下一首播放
break;
;
@Override
public void onReceive(Context context, Intent intent)
this.mContext = context;
String intentAction = intent.getAction();
//拔插耳机
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intentAction))
//插拔耳机的时候可以播放或者停止播放音乐
else if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) //点击耳机键
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN)
Click();
//
private void Click()
mSecondClickTime = mSaveFirstTime;
mFirstClickTime = System.currentTimeMillis();
mSaveFirstTime = mFirstClickTime;
long time = mFirstClickTime - mSecondClickTime;
int number = mClickNumber;
if (time > 0 && time < 700)
mHandler.removeMessages(MSG_CLICK_DEAL);
if (mClickNumber == 0)
mClickNumber = 1;
else if (number == 1)
mClickNumber = 2;
else if (number == 2)
mClickNumber = 0;
else
mClickNumber = 0;
mHandler.sendEmptyMessageDelayed(MSG_CLICK_DEAL, 900L);
以上是关于android 耳机按钮控制音乐播放的主要内容,如果未能解决你的问题,请参考以下文章