<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.hanqi.bluetooth.MainActivity" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="搜索蓝牙设备" android:onClick="bt_OnClick"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tvDevices" /> </LinearLayout>
package com.hanqi.bluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.Set; public class MainActivity extends AppCompatActivity { TextView tvDevices; BluetoothAdapter mBluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvDevices=(TextView)findViewById(R.id.tvDevices); //获取本地蓝牙适配器 mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> paireDevices=mBluetoothAdapter.getBondedDevices(); if (paireDevices.size()>0) { for (BluetoothDevice device:paireDevices) { tvDevices.append(device.getName()+":"+device.getAddress()); } } IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(receiver,filter); filter=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(receiver,filter); } public void bt_OnClick(View v) { setProgressBarIndeterminateVisibility(true); setTitle("正在扫描..."); if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } mBluetoothAdapter.startDiscovery(); } private final BroadcastReceiver receiver=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); if (device.getBondState()!=BluetoothDevice.BOND_BONDED) { tvDevices.append(device.getName()+":"+device.getAddress()); } }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarVisibility(false); setTitle("已搜索完成"); } } }; }