Androidはイヤホンのボタンの事件を監視します


仕事の中で、私たちは時々イヤホンのボタンの論理を処理して、主に2種類に分けて、1つは短いボタンで、1つは長いボタンです.
ヘッドホンのキーイベントを監視する方法は2つあります.
方法1: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>

注意この方法はイヤホンの短い押しイベントしか傍受できません.長い押しイベントを傍受したい場合は、方法2を使用してください.
方法2:onKeyDownメソッドの直接傍受
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_HEADSETHOOK == keyCode) { //      
			if (event.getRepeatCount() == 0) {  //      ,getRepeatCount      
				//  
			} else {
				//  
			}
		}
}