Android headset line control details, Bluetooth headset button monitoring (similar to cool dog line control effect)

Source: Internet
Author: User

Android headset line control details, Bluetooth headset button monitoring (similar to cool dog line control effect)


When the media button of the headset is clicked, the Android system sends a broadcast. The broadcast carries an Intent with the Action MEDIA_BUTTON. After listening to the broadcast, you can obtain the click events of the headset media buttons on your mobile phone.

There is an AudioManager class in Android, which maintains the distribution of MEDIA_BUTTON broadcasts. Therefore, to enable the headset button listening, you need to register a receiver for receiving the headset button-Click Event to AudioManager:


AudioManager audioManager = (AudioManager)context      .getSystemService(Context.AUDIO_SERVICE);ComponentName name = newComponentName(context.getPackageName(),      MediaButtonReceiver.class.getName());audioManager.registerMediaButtonEventReceiver(name);


The prototype of this method is:

Publicvoid registerMediaButtonEventReceiver (PendingIntent eventReceiver)

Added in API level 18

Registera component to be the sole receiver er of MEDIA_BUTTON intents. this is like registerMediaButtonEventReceiver (android. content. componentName), but allows the buttons to go to any PendingIntent. note that you shouldonly use this form if you know you will continue running for the full timeuntil unregistering the PendingIntent.



Target that will receive media button intents. The PendingIntent will be sent an ACTION_MEDIA_BUTTON event when a media button action occurs, with EXTRA_KEY_EVENT added and holding the key code of the media button that was pressed.

From the API notes, we can see that:

1. Register a MediaoButtonRecevie in the AudioManager object to make it the only receiver of MEDIA_BUTTON. That is to say, only I can receive the broadcast, and none of the others can receive the broadcast, otherwise, everyone will be confused;

2. The broadcast must be declared in the AndroidManifest. xml file. Otherwise, the MEDIA_BUTTON broadcast will not be listened.

Note: When we have registered the AudioManager media button receiver and the receiver is the only receiver of the media button, we need to cancel the registration without using the button listening:


AudioManager audioManager = (AudioManager)context    .getSystemService(Context.AUDIO_SERVICE);ComponentName name = newComponentName(context.getPackageName(),    MediaButtonReceiver.class.getName());audioManager.unregisterMediaButtonEventReceiver(name);


When a click event occurs on the headset media key, the Android system sends two broadcasts. The first is when the press is pressed, and the second is when the press is released, to accurately know how many media keys a user has clicked, you only need to process the click event when the buttons are released:


KeyEvent keyEvent = (KeyEvent) intent. getParcelableExtra (Intent. EXTRA_KEY_EVENT); // obtain the KeyEvent object if (keyEvent. getAction () = KeyEvent. ACTION_UP) {// process the click event here}


The following describes several classes used to achieve the line control effect:

1. Headset line control management tool class HeadSetUtil:


Package com. jph. lc; import android. content. componentName; import android. content. context; import android. media. audioManager; import android. util. log;/*** headset line control management tool class Singleton * @ author JPH * @ date 4:03:45 */public class HeadSetUtil {private static HeadSetUtil headSetUtil; private OnHeadSetListener headSetListener = null; public static HeadSetUtil getInstance () {if (headSetUtil = null) {headSetUtil = New HeadSetUtil ();} return headSetUtil;}/*** set this interface before you open the monitoring interface, otherwise, the setting is invalid * @ param headSetListener */public void setOnHeadSetListener (OnHeadSetListener headSetListener) {this. headSetListener = headSetListener;}/*** registers the receiver for MEDIA_BUTTON (register and enable the headset line control listener. Please call this method after setting the interface listening; otherwise, the interface is invalid) * @ param context */public void open (Context context) {if (headSetListener = null) {throw new IllegalStateException (pleas E set headSetListener);} AudioManager audioManager = (AudioManager) context. getSystemService (Context. AUDIO_SERVICE); ComponentName name = new ComponentName (context. getPackageName (), MediaButtonReceiver. class. getName (); audioManager. registerMediaButtonEventReceiver (name); Log. I (ksdinf, open);}/*** disable the headset line control listener * @ param context */public void close (Context context) {AudioManager audioManager = (AudioManager) Context. getSystemService (Context. AUDIO_SERVICE); ComponentName name = new ComponentName (context. getPackageName (), MediaButtonReceiver. class. getName (); audioManager. unregisterMediaButtonEventReceiver (name);}/*** delete a headset single-host double-click listener interface */public void delHeadSetListener () {this. headSetListener = null;}/*** obtain the headset. Click the double-click interface ** @ return */protected OnHeadSetListener getOnHeadSetListener () {return headSetListener ;}/** * Double-click the headset button to listen */public interface OnHeadSetListener {/*** and click trigger, the main thread. This interface is actually triggered after a click operation for 1 second because you need to determine whether the click is still monitored within 1 second. If yes, double-click */public void onClick (); /*** double-click the trigger. This interface is triggered in the main thread, so you can safely use */public void onDoubleClick ();/*** triple-click */public void onThreeClick ();}}
This class is mainly responsible for registration of the media key receiver and settings of the custom media key callback listener. This class contains an OnHeadSetListener interface. The onClick (), onDoubleClick (), and onThreeClick () methods in this interface will click events and double-click events respectively, and callback when a three-click event occurs. It should be noted that the click and double-click events will have a delay of one second, because there is still a reason to listen for the click in this one second. Of course, this is not an absolute one second, you can also customize events based on actual business needs. The class described below will unlock the principle of codoy wire control.


2. earphone media buttons broadcast receiver MediaButtonReceiver:


Package com. jph. lc; import java. util. timer; import java. util. timerTask; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. keyEvent; import com. jph. lc. headSetUtil. onHeadSetListener;/*** MEDIA_BUTTON headset media keys broadcast receiver * @ author JPH * @ Date2015-6-9 8:35:40 pm */publi C class MediaButtonReceiver extends BroadcastReceiver {private Timer timer = null; private OnHeadSetListener headSetListener = null; private static MTask myTimer = null;/** Number of clicks **/private static int clickCount; public MediaButtonReceiver () {timer = new Timer (true); this. headSetListener = HeadSetUtil. getInstance (). getOnHeadSetListener () ;}@ Overridepublic void onReceive (Context context, Intent intent) {Log. I (ksdinf, onReceive); String intentAction = intent. getAction (); if (Intent. ACTION_MEDIA_BUTTON.equals (intentAction) {KeyEvent keyEvent = (KeyEvent) intent. getParcelableExtra (Intent. EXTRA_KEY_EVENT); // obtain the KeyEvent object if (headSetListener! = Null) {try {if (keyEvent. getAction () = KeyEvent. ACTION_UP) {if (clickCount = 0) {// click clickCount ++; myTimer = new MTask (); timer. schedule (myTimer, 1000);} else if (clickCount = 1) {// double-click clickCount ++;} else if (clickCount = 2) {// three-click clickCount = 0; myTimer. cancel (); headSetListener. onThreeClick () ;}} catch (Exception e) {}} abortBroadcast (); // terminate broadcast (do not allow other programs to receive this broadcast and avoid interference )} /*** timer, used to delay 1 second to determine whether double-click or triple-click will occur */class MTask extends TimerTask {@ Overridepublic void run () {try {if (clickCount = 1) {mhHandler. sendEmptyMessage (1);} else if (clickCount = 2) {mhHandler. sendEmptyMessage (2);} clickCount = 0;} catch (Exception e) {// TODO: handle exception }}}; /*** the main purpose of this handle is to trigger the interface in the main thread *, and put the interface in the main thread for security reasons */Handler mhHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); if (msg. what = 1) {// click headSetListener. onClick ();} else if (msg. what = 2) {// double-click headSetListener. onDoubleClick ();} else if (msg. what = 3) {// three-click headSetListener. onThreeClick ();}}};}
This class is mainly responsible for receiving click events of media cases issued by the system, and processing the click events to achieve the effect of clicking, double-clicking, and triple-clicking. It should be noted that this class will obtain the OnHeadSetListener listener during instantiation. Therefore, you must set the OnHeadSetListener before calling the open method of the HeadSetUtil class. Otherwise, the media button event will not be processed.


There is an internal class named Mtask in this class, which is a scheduled task. The task will analyze whether double-clicking or triple-clicking occurs at the specified time.

In addition, this class also has a myHandler object, which is used to bring the callback listener to the UI thread for UI updates.

3. Listener usage class MainActivity:


Package com. jph. lc; import android. app. activity; import android. OS. bundle; import android. util. log; import android. widget. textView; import com. jph. lc. headSetUtil. onHeadSetListener;/*** headset line control instance, Bluetooth headset button listening (cool dog line control effect) * @ author JPH * @ Date2015-6-10 9:49:02 */public class MainActivity extends Activity {TextView txt = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); txt = (TextView) findViewById (R. id. text); HeadSetUtil. getInstance (). setOnHeadSetListener (headSetListener); HeadSetUtil. getInstance (). open (this) ;}@ Overrideprotected void onDestroy () {super. onDestroy (); HeadSetUtil. getInstance (). close (this);} OnHeadSetListener headSetListener = new OnHeadSetListener () {@ Overridepublic void onDoubleClick () {txt. setText (double-click); Log. I (ksdinf, double-click) ;}@ Overridepublic void onClick () {txt. setText (click); Log. I (ksdinf, click) ;}@ Overridepublic void onThreeClick () {txt. setText (three-click); Log. I (ksdinf, three-click );}};}


This section describes how to use a media button listener.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.