xml代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NewMainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="19dp"
android:text="搜索蓝牙" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button"
android:layout_marginBottom="14dp"
android:layout_marginLeft="45dp"
android:layout_marginStart="45dp"
android:layout_toEndOf="@+id/button"
android:layout_toRightOf="@+id/button"
android:text="初始状态" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/button"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:text="蓝牙设备如下:" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"
android:layout_below="@+id/textView"
tools:ignore="NestedScrolling" />
</RelativeLayout>
java代码
package com.automator.bluetooth;
import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.List;
public class NewMainActivity extends AppCompatActivity{
private BluetoothAdapter bluetoothAdapter;
private BluetoothManager bluetoothManager;
private TextView text1,text2,text3,text4;
private Button button;
private static final String TAG = "MainActivity";
private BluetoothDevice device;
ListView listView;
List<String> list = new ArrayList<>();
List<String> addList = new ArrayList<>();
String address = "";
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = findViewById(R.id.textView);
text2 = findViewById(R.id.textView2);
button = findViewById(R.id.button);
listView = findViewById(R.id.listView);
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null){
Toast.makeText(this,"设备不支持蓝牙", Toast.LENGTH_SHORT).show();
}
if (!bluetoothAdapter.isEnabled()){
bluetoothAdapter.enable();
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter);
IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver,filter1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermission();
text2.setText("正在搜索...");
list.clear();
}
});
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= 23) {
int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
Log.d(TAG, "没有权限,请求权限");
return;
} else {
bluetoothAdapter.startDiscovery();
}
Log.d(TAG, "已有定位权限");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
bluetoothAdapter.startDiscovery();
} else {
Log.d(TAG, "没有定位权限,请先开启!");
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@RequiresApi(api = Build.VERSION_CODES.R)
@SuppressLint("SetTextI18n")
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)){
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
list.add("\n" + device.getName() + "==>" + device.getAddress() + "\n");
addList.add(device.getAddress());
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewMainActivity.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice bluetoothDevice ;
bluetoothDevice = bluetoothAdapter.getRemoteDevice(addList.get(position));
bluetoothDevice.connectGatt(NewMainActivity.this, false, gattCallback);
address = addList.get(position);
Log.d("点击蓝牙", listView.getItemAtPosition(position) + "");
}
});
Log.d("搜索蓝牙设备如下", device.getName() + "==>" + device.getAddress());
}else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
text2.setText("搜索完成");
}
}
};
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService service : services) {
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
gatt.readCharacteristic(characteristic);
}
}
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
byte[] data = characteristic.getValue();
Log.d(TAG,"搜索蓝牙设备如下 onCharacteristicRead + " + address + " " + new String(data) + " " );
}
}
};
}
添加权限
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!--6.0之后需要定位权限-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />