Android7.0 应用连接蓝牙音箱(亲测可用)
前言
之前操作android蓝牙,都是直接进行数据流通讯,配对成功后接收方监听socket,发送方连接即可。
最近需要连接蓝牙音箱,和系统比较发现,蓝牙音箱存在已连接的状态,而部分android手机之间是不存在连接状态的。
因此将亲测代码贴出,本人萌新,欢迎探讨。
文章中用到的IBluetoothA2dp可在该路径下下载:
https://download.csdn.net/download/csdn_xiaozhe/10618842
至于aidl的使用方式,将在下一篇中记录。
正文
直接贴代码(蓝牙开启,搜索,配对过程省略)
private IBluetoothA2dp iBluetoothA2dp = null;
private BluetoothDevice mRemoteBluetoothDevice = null;
@Override
public void onCreate() {
//蓝牙开启,搜索,配对过程已省略,默认已经配对成功
if (mRemoteBluetoothDevice != null && mRemoteBluetoothDevice.getBondState()== BluetoothDevice.BONDED) {
bindA2dpService();
while(true) {
if (processMili < 30000) { //等待服务绑定超时时间
if (iBluetoothA2dp != null) {
try {
iBluetoothA2dp.connect(mRemoteBluetoothDevice);
} catch (Exception e) {
e.printStackTrace();
}
break;
} else {
processMili = System.currentTimeMillis() - startMili;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
Log.e("Altman","超时,此次连接失败");
break;
}
}
}
}
private void bindA2dpService(){
Intent intent = getExplicitIntent(this,new Intent(IBluetoothA2dp.class.getName()));
boolean success = this.bindService(intent , mServiceConnection, Context.BIND_AUTO_CREATE);
if (success) {
Log.e("Altman","只能证明,bindService执行成功,结果在回调函数中");
} else {
Log.e("Altman","只能证明,bindService执行失败");
}
}
public ServiceConnection mServiceConnection= new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
iBluetoothA2dp = IBluetoothA2dp.Stub.asInterface(service);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e("Altman","获取服务失败");
}
};
public Intent getExplicitIntent(Context context, Intent implicitIntent) {
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);
if (resolveInfo == null || resolveInfo.size() != 1) {
return null;
}
ResolveInfo serviceInfo = resolveInfo.get(0);
String packageName = serviceInfo.serviceInfo.packageName;
String className = serviceInfo.serviceInfo.name;
ComponentName component = new ComponentName(packageName, className);
Intent explicitIntent = new Intent(implicitIntent);
explicitIntent.setComponent(component);
return explicitIntent;
}