Android监听耳机按键事件

在工作中,我们有时候会处理到耳机按键的逻辑,主要分为两类,一种是短按,一种是长按。

监听耳机的按键事件的方法有两种:

方法一:注册监听Media Button的按键事件

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

public class MainActivity extends Activity {

	private AudioManager mAudioManager;
	private ComponentName mComponentName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        // AudioManager注册一个MediaButton对象
		mComponentName = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
	}
	
	

	@Override
	protected void onResume() {
		 mAudioManager.registerMediaButtonEventReceiver(mComponentName);
	     registerReceiver(headSetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
		super.onResume();
	}

	@Override
	protected void onPause() {
		// 取消注册
		mAudioManager.unregisterMediaButtonEventReceiver(mComponentName);
		unregisterReceiver(headSetReceiver);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		mAudioManager = null;
		mComponentName = null;
		super.onDestroy();
	}
	
	private final BroadcastReceiver headSetReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
				// phone headset plugged
				if (intent.getIntExtra("state", 0) == 1) {
					// do something
//					Log.d(TAG, "耳机检测:插入");
//					Toast.makeText(context, "耳机检测:插入", Toast.LENGTH_SHORT) .show();
					mAudioManager.registerMediaButtonEventReceiver(mComponentName);
					// phone head unplugged
				} else {
					// do something
//					Log.d(TAG, "耳机检测:没有插入");
//					Toast.makeText(context, "耳机检测:没有插入", Toast.LENGTH_SHORT).show();
					mAudioManager.unregisterMediaButtonEventReceiver(mComponentName);
				}
			}
		}
	};
MediaButtonReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

public class MediaButtonReceiver extends BroadcastReceiver {
	
	private static String TAG = "MediaButtonReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {

		// 获得Action
		String intentAction = intent.getAction();
		// 获得KeyEvent对象
		KeyEvent keyEvent = (KeyEvent) intent
				.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

		Log.i(TAG, "Action ---->" + intentAction + "  KeyEvent----->"
				+ keyEvent.toString());
		// 按下 / 松开 按钮
		int keyAction = keyEvent.getAction();

		if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)
				&& (KeyEvent.ACTION_DOWN == keyAction)) {
			// 获得按键字节码
			int keyCode = keyEvent.getKeyCode();

			// 获得事件的时间
			// long downtime = keyEvent.getEventTime();

			// 获取按键码 keyCode
//			StringBuilder sb = new StringBuilder();
//			// 这些都是可能的按键码 , 打印出来用户按下的键
//			if (KeyEvent.KEYCODE_MEDIA_NEXT == keyCode) {
//				sb.append("KEYCODE_MEDIA_NEXT");
//			}
			// 说明:当我们按下MEDIA_BUTTON中间按钮时,实际出发的是 KEYCODE_HEADSETHOOK 而不是
			// KEYCODE_MEDIA_PLAY_PAUSE
			if (KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE == keyCode) {
//				sb.append("KEYCODE_MEDIA_PLAY_PAUSE");
				
			}
			if (KeyEvent.KEYCODE_HEADSETHOOK == keyCode) {
//				sb.append("KEYCODE_HEADSETHOOK");
			}
			if (KeyEvent.KEYCODE_MEDIA_PREVIOUS == keyCode) {
//				sb.append("KEYCODE_MEDIA_PREVIOUS");
			}
			if (KeyEvent.KEYCODE_MEDIA_STOP == keyCode) {
//				sb.append("KEYCODE_MEDIA_STOP");
			}
			// 输出点击的按键码
//			Log.i(TAG, sb.toString());
//			Toast.makeText(context, sb.toString(), Toast.LENGTH_SHORT).show();
		} else if (KeyEvent.ACTION_UP == keyAction) {
			Log.i("chengjie", "aaa");
		}
	}
}
注意,在AndroidManifest.xml中定义
 <receiver android:name="com.lenovo.longexposure.MediaButtonReceiver" >
            <intent-filter android:priority="2147483647" >
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
 </receiver>

注意这种方法只能监听耳机的短按事件,如果想监听长按事件,请用方法二。

方法二:直接监听onKeyDown方法

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_HEADSETHOOK == keyCode) { //按下了耳机键
			if (event.getRepeatCount() == 0) {  //如果长按的话,getRepeatCount值会一直变大
				//短按
			} else {
				//长按
			}
		}
}










郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。