ANDROID_MARS学习笔记_S03_001_获取蓝牙匹配列表

一、代码

1.xml
(1)AndroidManifest.xml

增加

1 <uses-permission android:name="android.permission.BLUETOOTH"/>

 

2.java
(1)MainActivity.java

 1 package com.bluetooth1;
 2 
 3 import java.util.Iterator;
 4 import java.util.Set;
 5 
 6 import android.app.Activity;
 7 import android.bluetooth.BluetoothAdapter;
 8 import android.bluetooth.BluetoothDevice;
 9 import android.content.Intent;
10 import android.os.Bundle;
11 import android.view.View;
12 import android.view.View.OnClickListener;
13 import android.widget.Button;
14 
15 public class MainActivity extends Activity {
16 
17     private Button button = null;
18     @Override
19     protected void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_main);
22         
23         button = (Button)findViewById(R.id.buttonId);
24         button.setOnClickListener(new OnClickListener() {
25             @Override
26             public void onClick(View v) {
27                 //获得BluetoothAdapter对象,该API是android 2.0开始支持的
28                 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
29                 //adapter不等于null,说明本机有蓝牙设备
30                 if(adapter != null) {
31                     System.out.println("本机有蓝牙设备!");
32                     //如果蓝牙设备未开启
33                     if(!adapter.isEnabled()) {
34                         Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
35                         //请求开启蓝牙设备
36                         startActivity(intent);
37                     }
38                     //获得已配对的远程蓝牙设备的集合
39                     Set<BluetoothDevice> devices = adapter.getBondedDevices();
40                     if(devices.size() > 0) {
41                         for(Iterator<BluetoothDevice> it = devices.iterator() ; it.hasNext() ; ) {
42                             //打印出远程蓝牙设备的物理地址
43                             BluetoothDevice device = it.next();
44                             System.out.println(device.getAddress());
45                         }
46                     } else {
47                         System.out.println("还没有已配对的远程蓝牙设备!");
48                     }
49                 } else {
50                     System.out.println("本机没有蓝牙设备!");
51                 }
52             }
53         });
54     }
55 }

 

 

你可能感兴趣的:(ANDROID_MARS学习笔记_S03_001_获取蓝牙匹配列表)