我使用清单文件为ACTION_HEADSET_PLUG创建广播接收器。但是当耳机连接/断开连接时,我无法获得广播,为了能够接收ACTION_HEADSET_PLUG广播意图,我应该在清单文件中使用哪个permission?
发布于 2011-02-18 15:48:26
使用API 8,我无需创建服务或请求额外权限即可调用我的广播接收器。
您可以在main活动中定义一个内部类,类似于我在下面定义的类:
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()方法中动态注册了mine:
this.registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));确保您使用上下文的unregisterReceiver注销了BroadcastReceiver。在我的例子中,我是在onDestroy()方法中完成的。这应该就行了。
发布于 2010-12-15 04:48:41
这不是许可的问题,实际上是你如何注册接收者的问题。耳机插头动作广播只能由主动注册的接收者接收,如下所示:
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。
https://stackoverflow.com/questions/4202046
复制相似问题