一. 什么是蓝牙(Bluetooth)?java
1.1 BuleTooth是目前使用最普遍的无线通讯协议android
1.2 主要针对短距离设备通信(10m)网络
1.3 经常使用于链接耳机,鼠标和移动通信设备等.app
二. 与蓝牙相关的APIide
2.1 BluetoothAdapter:spa
表明了本地的蓝牙适配器xml
2.2 BluetoothDevice对象
表明了一个远程的Bluetooth设备blog
三. 扫描已经配对的蓝牙设备(1)部署
注:必须部署在真实手机上,模拟器没法实现
首先须要在AndroidManifest.xml 声明蓝牙权限
<user-permission android:name="android.permission.BLUETOOTH" />
配对蓝牙须要手动操做:
1. 打开设置--> 无线网络 --> 蓝牙 勾选开启
2. 打开蓝牙设置 扫描周围已经开启的蓝牙设备(能够与本身的笔记本电脑进行配对),点击进行配对
电脑上会弹出提示窗口: 添加设备
显示计算与设备之间的配对码,要求确认是否配对
手机上也会显示相似的提示.
四. 扫描已经配对的蓝牙设备(2)
4.1 得到BluetoothAdapter对象
4.2 判断当前移动设备中是否拥有蓝牙
4.3 判断当前移动设备中蓝牙是否已经打开
4.4 获得全部已经配对的蓝牙设备对象
import java.util.Iterator; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button button = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)findViewById(R.id.buttonId); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { //得到BluetoothAdapter对象,该API是android 2.0开始支持的 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); //adapter不等于null,说明本机有蓝牙设备 if(adapter != null){ System.out.println("本机有蓝牙设备!"); //若是蓝牙设备未开启 if(!adapter.isEnabled()){ Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //请求开启蓝牙设备 startActivity(intent); } //得到已配对的远程蓝牙设备的集合 Set<BluetoothDevice> devices = adapter.getBondedDevices(); if(devices.size()>0){ for(Iterator<BluetoothDevice> it = devices.iterator();it.hasNext();){ BluetoothDevice device = (BluetoothDevice)it.next(); //打印出远程蓝牙设备的物理地址 System.out.println(device.getAddress()); } }else{ System.out.println("尚未已配对的远程蓝牙设备!"); } }else{ System.out.println("本机没有蓝牙设备!"); } } }); } }