蓝牙的创建方法
蓝牙需要动态获取权限,使用getSystemService(BLUETOOTH_SERVICE);创建一个BluetoothManager的对象,然后使用BluetoothManager的对象.getAdapter();获取本地蓝牙对象,对本地的蓝牙进行操作。
蓝牙开启的方法
蓝牙是使用隐式意图跳转的,需要在addAction里添加对应的常量,然后使用广播接收者接收(需要动态注册),用startActivity(intent);方法发送。
代码
private void init(){
String[] s = new String[]{
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_FINE_LOCATION
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(s,100);
}
}
initBlueTooth();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//注册搜索蓝牙的广播
intentFilter.addAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//搜索结束
myReceiver = new MyReceiver(mapList,simpleAdapter,deviceList);
registerReceiver(myReceiver,intentFilter);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void initBlueTooth(){
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
adapter = bluetoothManager.getAdapter();
}
public void open(){
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
// intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(intent);
}
public void close(){
adapter.disable();
}
public void search(){
adapter.startDiscovery();
}