话不多说 直接上代码
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;
public class HeadsetPlugReceiver extends BroadcastReceiver {
private HeadsetPlugListener mHeadsetPlugListener;
public HeadsetPlugReceiver(HeadsetPlugListener headsetPlugListener) {
this.mHeadsetPlugListener = headsetPlugListener;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//判断是否有蓝牙设备连接
if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
int state = adapter.getProfileConnectionState(BluetoothProfile.HEADSET);
if (BluetoothProfile.STATE_CONNECTED == state) {
mHeadsetPlugListener.onHeadsetPlug(true);
}
if (BluetoothProfile.STATE_DISCONNECTED == state) {
mHeadsetPlugListener.onHeadsetPlug(false);
}
}
//判断是否有有线耳机连接
} else if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
if (intent.hasExtra("state")) {
if (intent.getIntExtra("state", 0) == 0) {
// 外放
mHeadsetPlugListener.onHeadsetPlug(false);
} else if (intent.getIntExtra("state", 0) == 1) {
// 耳机
mHeadsetPlugListener.onHeadsetPlug(true);
}
}
}
}
//可以在页面进入时 通过这个来判断是否有耳机连接 之后想判断又没有耳机插入需要通过上面的OnReceive
public int getHeadSetStatus(Context context) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); // 获取声音管理器
if (audioManager.isWiredHeadsetOn()) { // 有限耳机是否连接
return 1;
}
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 蓝牙耳机
if (bluetoothAdapter == null) { // 若蓝牙耳机无连接
return -1;
} else if (bluetoothAdapter.isEnabled()) {
int a2dp = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP); // 可操控蓝牙设备,如带播放暂停功能的蓝牙耳机
int headset = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET); // 蓝牙头戴式耳机,支持语音输入输出
int health = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH); // 蓝牙穿戴式设备
// 查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态
int flag = -1;
if (a2dp == BluetoothProfile.STATE_CONNECTED) {
flag = a2dp;
} else if (headset == BluetoothProfile.STATE_CONNECTED) {
flag = headset;
} else if (health == BluetoothProfile.STATE_CONNECTED) {
flag = health;
}
// 说明连接上了三种设备的一种
if (flag != -1) {
return 2;
}
}
return -2;
}
public interface HeadsetPlugListener {
void onHeadsetPlug(boolean isPlug);// true说明有耳机 false说明没有耳机
}
//注册蓝牙连接状态
public void registRecevier(Context context){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
context.registerReceiver(this, intentFilter);
}
}