Which permission required in order to get ACTION_HEADSET_PLUG inside broadcast receiver

后端 未结 2 471
日久生厌
日久生厌 2021-01-03 14:47

I am using the manifest file for creating broadcast receiver, for ACTION_HEADSET_PLUG. But I can\'t get the broadcast when headset is connect/disconnect, Which

2条回答
  •  离开以前
    2021-01-03 15:38

    With API 8, I got my broadcast receiver called without creating a service or requesting for extra permissions.

    You can define an inner class within your main activity similar to the one I've defined below:

    public class HeadSetBroadCastReceiver extends BroadcastReceiver
        {
    
            @Override
            public void onReceive(Context context, Intent intent) {
    
                // TODO Auto-generated method stub
                String action = intent.getAction();
                Log.i("Broadcast Receiver", action);
                if( (action.compareTo(Intent.ACTION_HEADSET_PLUG))  == 0)   //if the action match a headset one
                {
                    int headSetState = intent.getIntExtra("state", 0);      //get the headset state property
                    int hasMicrophone = intent.getIntExtra("microphone", 0);//get the headset microphone property
                    if( (headSetState == 0) && (hasMicrophone == 0))        //headset was unplugged & has no microphone
                    {
                                   //do whatever
                    }
                }           
    
            }
    
        }
    

    Then, register your broadcast receiver either dynamically or statically. I registered mine dynamically in my Activity's onCreate() method:

    this.registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    

    Make sure that you unregister your BroadcastReceiver with the Context's unregisterReceiver. In my case, I did this in the onDestroy() method. That should do it.

提交回复
热议问题