Android耳机按键监听

MediaButtonService.java:

//耳机按键监听的Receiver注册比较特殊。

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;

public class MediaButtonService extends Service {

 
 private AudioManager mAudioManager;
 private ComponentName rec;
 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }
 
 @Override
 public void onCreate() {
  // TODO Auto-generated method stub
  super.onCreate();
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
      rec = new ComponentName(getPackageName(),
                 MediaButtonIntentReceiver.class.getName());
      mAudioManager.registerMediaButtonEventReceiver(rec);
 }
 
 @Override
 public void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  mAudioManager.unregisterMediaButtonEventReceiver(rec);
 }

}

 

MediaButtonIntentReceiver.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 MediaButtonIntentReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  String intentAction = intent.getAction();
  if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
   KeyEvent event = (KeyEvent) intent
     .getParcelableExtra(Intent.EXTRA_KEY_EVENT);
   if (event == null) {
    return;
   }

   int keycode = event.getKeyCode();
   int action = event.getAction();
   long eventtime = event.getEventTime();

   //按键处理逻辑

   // single quick press: pause/resume.
   // double press: next track
   // long press: start auto-shuffle mode.

   String command = null;
   switch (keycode) {
   case KeyEvent.KEYCODE_HEADSETHOOK:
   case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
//耳机中间按键,可作为来电接听键,还可以作为音乐 播放/暂停 切换按键。

    if (action == KeyEvent.ACTION_DOWN)
     Toast.makeText(context, context.getResources().getString(R.string.media_but_res), Toast.LENGTH_SHORT).show();
    break;
   }

  }
 }
}

AndroidManifest.xml:

           android:enabled="true">
           
               
           

       

        

你可能感兴趣的:(android)