为了在广播接收器中获得ACTION_HEADSET_PLUG所需的权限

时间:2010-11-17 06:31:24

标签: android android-manifest

我正在使用清单文件为ACTION_HEADSET_PLUG创建广播接收器。 但是当耳机连接/断开时,我无法接收广播, 我应该在清单文件中使用哪个permission以便能够接收ACTION_HEADSET_PLUG广播意图?

2 个答案:

答案 0 :(得分:4)

使用API​​ 8,我在没有创建服务或请求额外权限的情况下调用了我的广播接收器。

您可以在主活动中定义一个内部类,类似于我在下面定义的类:

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

        }

    }

然后,动态或静态注册您的广播接收器。我在我的Activity的onCreate()方法中动态注册了我的:

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

确保使用Context的unregisterReceiver取消注册BroadcastReceiver。就我而言,我在onDestroy()方法中做到了这一点。应该这样做。

答案 1 :(得分:3)

这不是一个许可的事情,它实际上是你注册接收器的一个问题。耳机插头动作广播只能由积极注册的接收器接收,如下所示:

registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));

这意味着您需要保持一个服务,该服务保存对接收者的引用,并在服务被终止时取消注册。最后,注册接收器的服务也需要在启动时启动;你用另一个截取android.intent.action.BOOT_COMPLETED意图的接收器做的。对于此部分,您需要使用android.permission.RECEIVE_BOOT_COMPLETED权限。

有关执行此操作的服务的完整示例,您可以查看app I wrote that does just that