我正在使用清单文件来创建广播接收器,用于ACTION_HEADSET_PLUG
。
但是当耳机连接/断开时我无法收到广播,
哪个permission
我应该在清单文件内使用以便能够接收ACTION_HEADSET_PLUG
广播意图?
通过 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() 方法中执行此操作。应该可以做到这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)