首页 > 代码库 > 蓝牙技术(一)

蓝牙技术(一)

技术分享

第二种:不会有系统的提示界面

技术分享

 1 //搜索蓝牙设备
 2 public class MainActivity extends ActionBarActivity {
 3     private BluetoothAdapter adapter;
 4     TextView textDevice;
 5 
 6     @Override
 7     protected void onCreate(Bundle savedInstanceState) {
 8         super.onCreate(savedInstanceState);
 9         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
10         setContentView(R.layout.fragment_main);
11         textDevice = (TextView) findViewById(R.id.tv);
12         adapter = BluetoothAdapter.getDefaultAdapter();
13         Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
14         if (pairedDevices.size() > 0) {
15             for (BluetoothDevice device : pairedDevices) {
16 
17                 textDevice.append(device.getName() + ":" + device.getAddress());
18 
19             }
20         }
21         // 设备被找到--发送广播
22         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
23         this.registerReceiver(receiver, filter);
24         // 全部搜索完发送--广播
25         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
26         this.registerReceiver(receiver, filter);
27     }
28 
29     public void click(View view) {
30         setProgressBarIndeterminateVisibility(true);
31         setTitle("正在扫描。。。");
32         if (adapter.isDiscovering()) {
33             adapter.cancelDiscovery();
34         }
35         adapter.startDiscovery();
36 
37     }
38 
39     private final BroadcastReceiver receiver = new BroadcastReceiver() {
40 
41         @Override
42         public void onReceive(Context context, Intent intent) {
43             // TODO Auto-generated method stub
44             String action = intent.getAction();
45             if (BluetoothDevice.ACTION_FOUND.equals(action)) {
46                 BluetoothDevice device = intent
47                         .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
48                 if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
49                     textDevice.append(device.getName() + ":"
50                             + device.getAddress() + "\n");
51 
52                 }
53 
54             } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
55                     .equals(action)) {
56                 setProgressBarVisibility(false);
57                 setTitle("完成");
58             }
59         }
60 
61     };
62 }

 

蓝牙技术(一)