效果:
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
private List<String> list;
private RecyclerView recyclerView;
private MyRecycleViewAdapter adapter;
private Button btn;
BluetoothAdapter btAdapt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initView() {
list=new ArrayList<>();
recyclerView=findViewById(R.id.main_device_listview);
btn=findViewById(R.id.main_btn_start);
adapter=new MyRecycleViewAdapter(this,list);
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
private void initData() {
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (btAdapt.getState() != BluetoothAdapter.STATE_ON) {// 如果蓝牙还没开启
Toast.makeText(getBaseContext(), "请先开启蓝牙", Toast.LENGTH_SHORT).show();
return;
}
if (!btAdapt.isDiscovering()) {
list.clear();
addPairedDevice();
btAdapt.startDiscovery();
}
}
});
btAdapt = BluetoothAdapter.getDefaultAdapter();
if (btAdapt == null) {
Toast.makeText(getBaseContext(), "您的机器上没有发现蓝牙适配器,本程序将不能运行!", Toast.LENGTH_SHORT).show();
this.finish();
}
// 注册Receiver来获取蓝牙设备相关的结果
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND); // 用BroadcastReceiver来取得搜索结果
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(searchDevices, intent);
addPairedDevice();
}
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) { //found device
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String str = device.getName() + "|" + device.getAddress();
Log.e(TAG, "onReceive str: "+str );
if (list.indexOf(str) == -1)// 防止重复添加
list.add(str); // 获取设备名称和mac地址
adapter.UpdataList(list);
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
Toast.makeText(getBaseContext(), "正在扫描", Toast.LENGTH_SHORT).show();
btn.setText("正在扫描");
btn.setTextColor(Color.RED);
} else if (action
.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
btn.setText("扫描设备");
btn.setTextColor(Color.BLACK);
Toast.makeText(getBaseContext(), "扫描完成,点击列表中的设备来尝试连接", Toast.LENGTH_SHORT).show();
}
}
};
// 增加配对设备
private void addPairedDevice() {
Set<BluetoothDevice> pairedDevices = btAdapt.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
String str = device.getName() + "|" + device.getAddress();
list.add(str);
adapter.notifyDataSetChanged();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
}