Android:蓝牙耳机断开连接,音频播放器暂停播放
实现此功能,需要提前知道以下几点:
- 蓝牙断开连接时,系统会自动发送广播。android端所要做的就是监听、接收广播和后续处理;
- 监听蓝牙状态变化,需要在AndroidManifest.xml中申请权限;
要实现蓝牙耳机断开连接后,音频播放器自动暂定播放的功能,总结下来一共以下几步:
第一步:申请权限
在工程的AndroidManifest.xml中,添加以下代码:
<manifast xxx>
...
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
...
</manifast>
第二步:注册和注销蓝牙的广播接收器
1. 注册广播接收器
在工程的合适位置(构造函数、onCreate方法中等),此例中是打开音频播放器时,添加如下代码:
xxActivity.registerReceiver(bluetoothReceiver, new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED));
其中,xxActivity是自行创建的Activity或Context对象;bluetoothReceiver是即将在第三步中创建的广播接收器;BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED表明我们监听的是蓝牙连接状态的变化。
2. 注销蓝牙的广播接收器
在不需要监听蓝牙状态变化的时候,需要注销蓝牙的广播接收器。此例中是当退出音频播放时,注销蓝牙的广播接收器。代码为:
xxActivity.unregisterReceiver(bluetoothReceiver);
xxActivity和bluetoothReceiver的解释同上。
第三步:创建蓝牙状态变化的接收器,实现功能
首先提供带打印日志信息的代码,通过手机蓝牙与蓝牙耳机的断开和链接,查看日志信息。因为需要确保音频播放时,蓝牙从“连接”–>“断开”时才暂停音频播放,故需要同时满足“蓝牙状态变化”且“当前蓝牙状态为未连接”两个条件。
private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
Log.e("bluetooth", "BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED");
}
int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0);
switch (bluetoothState) {
case BluetoothAdapter.STATE_CONNECTED:
Log.i("bluetooth", "STATE_CONNECTED");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.i("bluetooth", "STATE_CONNECTING");
break;
case BluetoothAdapter.STATE_DISCONNECTED:
Log.i("bluetooth", "STATE_DISCONNECTED");
break;
case BluetoothAdapter.STATE_DISCONNECTING:
Log.i("bluetooth", "STATE_DISCONNECTING");
break;
default:
Log.i("bluetooth", "DEFAULT");
break;
}
if(action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED) && bluetoothState==BluetoothAdapter.STATE_DISCONNECTED){
pauseMusic();
}
}
};
精简后的实际代码如下:
private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0);
if(action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED) && bluetoothState==BluetoothAdapter.STATE_DISCONNECTED){
pauseMusic();
}
}
};