在我的应用中,我希望用户可以通过蓝牙、耳机和扬声器收听音频,因此我提供了一个微调器,如果连接了蓝牙,则微调器添加蓝牙,同时连接耳机,微调器也添加耳机。
>但是当我在具体启动服务以注册蓝牙和耳机广播接收器时 并运行应用程序,即使设备未连接到蓝牙和耳机设备或从它们中拔出,我也会让耳机从耳机广播接收器中拔出动作。
创建
startService(Intent(this, HeadsetService::class.java))
if (AppUtils.isBluetoothSupported(packageManager)) {
startService(Intent(this, BluetoothService::class.java))
}
破坏
stopService(Intent(this, HeadsetService::class.java))
stopService(Intent(this, BluetoothService::class.java))
耳机服务
public class HeadsetService extends Service {
private HeadsetUtility mHeadsetUtility;
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
initHeadsetBroadcastReceiver();
}
public void onDestroy() {
stopHeadsetBroadcastReceiver();
super.onDestroy();
}
private void initHeadsetBroadcastReceiver() {
if (this.mHeadsetUtility == null) {
this.mHeadsetUtility = new HeadsetUtility();
Log.e("videocall","headsetservice");
registerReceiver(this.mHeadsetUtility, HeadsetUtility.getIntentFilter());
}
}
private void stopHeadsetBroadcastReceiver() {
HeadsetUtility headsetUtility = this.mHeadsetUtility;
if (headsetUtility != null) {
unregisterReceiver(headsetUtility);
}
}
}
耳机广播
public final class HeadsetUtility extends BroadcastReceiver {
private static final String TAG = "HTEventReceiver";
private static boolean isHeadsetPluggedIn = false;
public static IntentFilter getIntentFilter() {
return new IntentFilter(Intent.ACTION_HEADSET_PLUG);
}
public static boolean isIsHeadsetPluggedIn() {
return isHeadsetPluggedIn;
}
public static void setIsHeadsetPluggedIn(boolean z) {
isHeadsetPluggedIn = z;
}
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == null) {
} else if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int intExtra = intent.getIntExtra("state", -1);
switch (intExtra) {
case 0:
headsetIsPluggedOut();
return;
case 1:
headsetIsPluggedIn();
return;
default:
setIsHeadsetPluggedIn(false);
return;
}
}
}
private void headsetIsPluggedIn() {
setIsHeadsetPluggedIn(true);
AppUtils.setmAudioSource(AppUtils.AudioSource.HEADSET);
Log.e("videocall","headsetservice1");
RxBus.publish(new RxEvent.EventAudioBroadcast(new Event_AudioSource(AppUtils.AudioSource.HEADSET,1)));
}
private void headsetIsPluggedOut() {
setIsHeadsetPluggedIn(false);
if (BluetoothUtility.isIsBluetoothConnected()) {
AppUtils.setmAudioSource(AppUtils.AudioSource.BLUETOOTH);
} else {
AppUtils.setmAudioSource(AppUtils.AudioSource.SPEAKER);
}
Log.e("videocall","headsetservice2");
RxBus.publish(new RxEvent.EventAudioBroadcast(new Event_AudioSource(AppUtils.AudioSource.HEADSET,2)));
}
}
清单
<service android:name=".utils.BluetoothService" />
<service android:name=".utils.HeadsetService" />
在清单中我没有注册广播,我已经使用意图过滤器注册了广播
所以,我的问题是当应用程序启动时服务启动并注册广播,我从广播中拔出耳机并调用耳机IsPluggedOut(),即使设备未连接到蓝牙和耳机设备或拔出来自他们
请提出建议