gpt4 book ai didi

android - 用于拔下耳机的 BroadcastReceiver

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:52:02 27 4
gpt4 key购买 nike

您好,我正在开发一个应用程序,当耳机从手机上取下时会生成一个事件。我创建了一个接收方法为的广播接收器

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub
String action = intent.getAction();
Log.i("Broadcast Receiver", "Hello");
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
}
}

}

调用这个方法如下

 IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
HeadSetBroadCastReceiver receiver = new HeadSetBroadCastReceiver();
registerReceiver( receiver, receiverFilter );

我也在 list 中将其注册为

   <receiver android:name=".HeadsetBroadCastReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_HEADSET_PLUG"/>
</intent-filter>
</receiver>

和权限

但这行不通,谁能指导我解决这个问题?

最佳答案

这是一个棘手的问题,但您可以使用 BroadCast 作为 Following 与我一起工作在您的 Activity

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new HeadSetReceiver();
}

并在 onResume() 方法中注册您的广播

public void onResume() {
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(myReceiver, filter);
super.onResume();
}

然后在你的 Activity 中声明你的 BroadCast

private class HeadSetReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d(TAG, "Headset unplugged");
break;
case 1:
Log.d(TAG, "Headset plugged");
break;
}
}
}
}

希望对你有帮助,,,

关于android - 用于拔下耳机的 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11716275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com