这边由于我不知道我们公司的设备代码怎么设计的,所以不太清楚通用性如何,不过一般而言应该差不多吧。
首先我自定义了一个蓝牙连接管理的类,初始化的参数为Activity的context(这里我写的很随意,理论上这个类写在Service中更好):
public class BTManager {
private Context context = null;
private BluetoothAdapter adapter = null;
private BroadcastReceiver receiver = null;
private BTService bts = null;
// 初始化
public BTManager(Context context) {
this.context = context;
initAdapter();
initRecevier();
}
}
首先判断手机支不支持蓝牙功能,如果支持则开启蓝牙
// 看是否支持蓝牙
private void initAdapter() {
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
Toast.makeText(context, "该设备不支持蓝牙!", Toast.LENGTH_SHORT).show();
return;
}
enabledBT();
}
// 开启蓝牙
private void enabledBT() {
if (!adapter.isEnabled()) {
Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivity(mIntent);
}
}
然后初始化广播,这个广播是要给Acitivty注册的,用来通知界面蓝牙连接的状态:
// 初始化广播
private void initRecevier() {
if(receiver == null){
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String actionName = intent.getAction();
if (actionName.equals("android.bluetooth.device.action.FOUND")) {
// 获取找到设备的对象
BluetoothDevice device = (BluetoothDevice) intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 如果找到的设备和想要搜索的设备名一致,就发送找到广播
if (device.getName() != null