当前位置: 首页 > 图灵资讯 > 技术篇> [android]使用线控耳机来操控应用功能

[android]使用线控耳机来操控应用功能

来源:图灵教育
时间:2023-06-15 09:26:30

使用线控耳机控制应用功能

实现原则:通过广播拦截实现。

(一)定义一个广播拦截器,用于拦截线控耳机按钮产生的广播事件。

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.KeyEvent;public class MediaButtonReceiver extends BroadcastReceiver {/** * Handler */private Handler handler;/** * 构造器. * @param handler */public MediaButtonReceiver(Handler handler) {this.handler = handler;}@Overridepublic void onReceive(Context context, Intent intent) {boolean isActionMediaButton = Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction());if(!isActionMediaButton) return;KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);if(event==null) return;boolean isActionUp = (event.getAction()==KeyEvent.ACTION_UP);if(!isActionUp) return;int keyCode = event.getKeyCode();long eventTime = event.getEventTime()-event.getDownTime();//按下按钮到松开时间Message msg = Message.obtain();msg.what = 100;Bundle data = new Bundle();data.putInt("key_code", keyCode);data.putLong("event_time", eventTime);msg.setData(data);handler.sendMessage(msg);//终止广播(不要让其他程序收到这个广播,以免干扰)abortBroadcast();}}

(二)主程序的处理:

(1)定义和注册广播服务

///初始化Handler对象    MyHandler handler = new MyHandler();    ////初始化媒体(耳机)广播对象.    MediaButtonReceiver mediaButtonReceiver = new MediaButtonReceiver(handler);    ///注册媒体(耳机)广播对象    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);    intentFilter.setPriority(100);    registerReceiver(mediaButtonReceiver, intentFilter);

(2)定义MyHandler和处理广播发回的消息:

private class MyHandler extends Handler{@Overridepublic void handleMessage(Message msg) {int what = msg.what;switch(what){case 100:///单击按键广播Bundlele data = msg.getData();//按键值int keyCode = data.getInt("key_code");///按键时间long eventTime = data.getLong("event_time");//设置超过2000毫秒,触发长按事件boolean isLongPress = (eventTime>2000);switch(keyCode){case KeyEvent.KEYCODE_HEADSETHOOK:///播放或暂停caseecase KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:///播放或暂停playOrPause();break;//短按=播放下一首音乐,长按=当前音乐快进caseee KeyEvent.KEYCODE_MEDIA_NEXT:if(isLongPress){fastNext(1);////自定义}else{playNext();////自定义}break;//短按=播放上一首音乐,长按=当前音乐快退casee KeyEvent.KEYCODE_MEDIA_PREVIOUS:if(isLongPress){fastPrevious(1);////自定义}else{playPrevious();////自定义}break;}break;default://其他消息-扔回上层处理super.handleMessage(msg);}}}

(3)退出应用程序时,别忘了取消注册广播拦截器。

unregisterReceiver(mediaButtonReceiver);