一、打开蓝牙权限
操作蓝牙之前必须先要注册蓝牙权限。在AndroidManifest.xml
文件中注册权限:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" ></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH" ></uses-permission>
二、动态申请蓝牙权限
某些android版本中蓝牙权限需要动态申请一次,调用下面的方法:
private void permission_request(){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH}, 1);
}
申请结果会调用下面的回调函数:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode==1){
for (int i=0;i<grantResults.length;i++){
if (grantResults[i]!=0){ //权限成功
System.exit(0);
}
}
}
}
三、蓝牙操作
蓝牙操作我直接封装了一个类,可以直接调用:
public class Bluetooth {
private static final String TAG="Bluetooth";
private static BluetoothSocket mmSocket;
private static BluetoothDevice mmDevice;
private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
private static InputStream mmInStream;
private static OutputStream mmOutStream;
public Bluetooth(BluetoothDevice device){
mmDevice = device;
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID
.fromString(SPP_UUID));
} catch (IOException e) {
Log.d(TAG, "create() failed", e);
}
mmSocket = tmp;
new Thread(new Runnable() {
@Override
public void run() {
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
Log.e(TAG, "unable to connect() socket", e);
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
}
return;
}
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[256*4];
int bytes;
StringBuilder stringBuilder = new StringBuilder();
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
if(mmInStream==null)
break;
bytes = mmInStream.read(buffer);
String str = new String(buffer,0,bytes,"ascii");
Log.d("XP",str);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}catch (RuntimeException e){
Log.e(TAG, "disconnected", e);
break;
}
}
}
}).start();
}
}).start();
}
//蓝牙发送数据
public static void bluetooth_write_data(byte[] buffer) {
try {
if(mmOutStream!=null)
mmOutStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
//判断蓝牙是否已经连接
public static Boolean bluetooth_is_connect(){
if (mmSocket!=null)
return true;
else
return false;
}
//关闭连接
public static void bluetooth_close_connect() {
try {
if (mmSocket!=null){
mmSocket.close();
mmSocket=null;
}
if(mmInStream!=null){
mmInStream.close();
mmInStream=null;
}
if(mmOutStream!=null){
mmOutStream.close();
mmOutStream=null;
}
mmDevice=null;
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
四、蓝牙具体操作流程
1、首先判断蓝牙是否打开,如果没有打开就打开蓝牙
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
2.点击按钮开始扫描蓝牙设备
@Override
public void onClick(View view) {
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
3.注册一个监听器获取扫描设备结果
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
myActivity.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
myActivity.registerReceiver(mReceiver, filter);
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ConnectShowInfo connectShowInfo = new ConnectShowInfo();
connectShowInfo.blueToothName=device.getName();//获取蓝牙名称
connectShowInfo.blueToothAddr=device.getAddress();//获取蓝牙地址
int rssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);//获取额外rssi值
connectShowInfo.singleStrength = rssi+"dB";
connectShowInfolist.add(connectShowInfo);
connectListView.setAdapter(connectShowInfoAdapter);
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
}
}
};
4.点击扫描到的设备开始连接
mBtAdapter.cancelDiscovery();//取消扫描
address = connectShowInfolist.get(i).blueToothAddr; //获取点击的地址
test.get_connect_address(address);//开始连接
public void get_connect_address(String addr) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(addr);
if(bluetooth.bluetooth_is_connect()) { //蓝牙已经连接
bluetooth.bluetooth_close_connect();
bluetooth=null;
}
if(bluetooth==null)
bluetooth = new Bluetooth(device);//调用前面那个类开始连接
}