这允许需要为了得到ACTION_HEADSET_PLUG广播接收机内接收机、ACTION_HEADSET_PLUG

2023-09-06 05:55:02 作者:該亽已濄期

我现在用的是清单文件用于创建广播​​接收器,用于 ACTION_HEADSET_PLUG 。 但我不能得到广播时,耳机连接/断开, 其中许可我应该清单文件中使用,以便能够接收 ACTION_HEADSET_PLUG 广播意图是什么?

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 permission should I use inside the manifest file in order to be able to receive ACTION_HEADSET_PLUG broadcast intent?

推荐答案

通过API 8,我得到了我的广播接收器叫,而无需创建一个服务或请求额外的权限。

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
                }
            }           

        }

    }

于是,无论是动态或静态注册的广播接收器。我动态在我活动的onCreate()方法进行注册矿:

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));

请确保您注销您的BroadcastReceiver与上下文的unregisterReceiver。以我为例,我在的onDestroy()方法,这样做。这应该做到这一点。

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.