Android系统中的蓝牙连接程序编写实例教程
bluetooth结构
1、java层
frameworks/base/core/java/android/bluetooth/
包含了bluetooth的java类。
2、jni层
frameworks/base/core/jni/android_bluetooth_开头的文件
定义了bluez通过jni到上层的接口。
frameworks/base/core/jni/android_server_bluetoothservice.cpp
调用硬件适配层的接口system/bluetooth/bluedroid/bluetooth.c
3、bluez库
external/bluez/
这是bluez用户空间的库,开源的bluetooth代码,包括很多协议,生成libbluetooth.so。
4、硬件适配层
system/bluetooth/bluedroid/bluetooth.c
包含了对硬件操作的接口
system/bluetooth/data/*
一些配置文件,复制到/etc/bluetooth/。
还有其他一些测试代码和工具。
简略介绍bluetooth开发使用到的类
1、bluetoothadapter,蓝牙适配器,可判断蓝牙设备是否可用等功能。
常用方法列举如下:
canceldiscovery() ,取消搜索过程,在进行蓝牙设备搜索时,如果调用该方法会停止搜索。(搜索过程会持续12秒)
disable()关闭蓝牙,也就是我们常说的禁用蓝牙。
enable()打开蓝牙,这个方法打开蓝牙但不会弹出提示,正常流程操作下,我们会让系统提示用户是否打开蓝牙设备。如下两行代码可轻松搞定。
intent enabler=new intent(bluetoothadapter.action_request_enable);
startactivityforresult(enabler,recode);//同startactivity(enabler);(在主activity启动一个二级activity,recode一般等于3,一定记得要在androidmanifest.xml里面添加蓝牙权限)
getaddress()获取本地蓝牙地址
getdefaultadapter()获取默认bluetoothadapter,实际上,也只有这一种方法获取bluetoothadapter
getname()获取本地蓝牙名称
getremotedevice(string address)根据蓝牙地址获取远程蓝牙设备
getstate()获取本地蓝牙适配器当前状态(感觉可能调试的时候更需要)
isdiscovering()判断当前是否正在查找设备,是返回true
isenabled()判断蓝牙是否打开,已打开返回true,否则,返回false
listenusingrfcommwithservicerecord(string name,uuid uuid)根据名称,uuid创建并返回
bluetoothserversocket,这是创建bluetoothsocket服务器端的第一步
startdiscovery()开始搜索,这是搜索的第一步
2.bluetoothdevice看名字就知道,这个类描述了一个蓝牙设备
createrfcommsockettoservicerecord(uuiduuid)根据uuid创建并返回一个bluetoothsocket
这个方法也是我们获取bluetoothdevice的目的——创建bluetoothsocket
这个类其他的方法,如getaddress(),getname(),同bluetoothadapter
这个类有几个隐藏方法,涉及到蓝牙的自动配对,setpin,createbond,cancelpairinguserinput,等方法(需要通过java的反射,调用这几个隐藏方法)
3.bluetoothserversocket如果去除了bluetooth相信大家一定再熟悉不过了,既然是socket,方法就应该都差不多,
这个类一种只有三个方法
两个重载的accept(),accept(inttimeout)两者的区别在于后面的方法指定了过时时间,需要注意的是,执行这两个方法的时候,直到接收到了客户端的请求(或是过期之后),都会阻塞线程,应该放在新线程里运行!
还有一点需要注意的是,这两个方法都返回一个bluetoothsocket,最后的连接也是服务器端与客户端的两个bluetoothsocket的连接
close()关闭!
4.bluetoothsocket,跟bluetoothserversocket相对,是客户端
一共5个方法,不出意外,都会用到
close(),关闭
connect()连接
getinptustream()获取输入流
getoutputstream()获取输出流
getremotedevice()获取远程设备,这里指的是获取bluetoothsocket指定连接的那个远程蓝牙设备
二、蓝牙设备的发现、查找。
1.基于安全性考虑,设置开启可被搜索后,android系统会默认给出120秒的时间,其他设备能在这120秒内搜索到它。
intent enable = new intent(bluetoothadapter.action_request_discoverable);
startactivityforresult(enalbe,request_discoverable);
2.搜索蓝牙设备
bluetoothadapter _bluetooth = bluetoothadapter.getdefaultadapter();
_bluetooth.startdiscovery();
3.关闭蓝牙设备
bluetoothadapter _bluetooth = bluetoothadapter.getdefaultadapter();
_bluetooth.disable();
4.创建蓝牙客户端
bluetoothsocket socket = device.createrfcommsockettoservicerecord(uuid.fromstring(uuid号));
socket.connect();
4.创建蓝牙服务端
bluetoothserversocket _serversocket = _bluetooth.listenusingrfcommwithservicerecord(服务端名称,uuid.fromestring(uuid号));
bluetoothsocket socket = _serversocket.accept();
inputstream inputstream = socket.getinputstream();
tcp/ip通信相关代码实现
注:tcp_ip模块需要在系统setting模块中,完成蓝牙的配对,只有配对成功的,才能进行socket通信(具体如何配对和如何自动配对,将在bluetoot3或者4中进行讲解)
andridmanifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.thecaseforbluetooth" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="15" /> <uses-permission android:name="android.permission.bluetooth_admin" /> <uses-permission android:name="android.permission.bluetooth" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".bluetoothactivity" android:label="@string/title_activity_bluetooth" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest>
main.xml
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearlayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnsearch" android:text="查找设备" /> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnexit" android:text="退出应用" /> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btndis" android:text="设置可被发现" /> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnserver" android:text="启动服务端" /> <togglebutton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tbtnswitch" android:text="开/关 蓝牙设备" /> <listview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/lvdevices" /> </linearlayout>
bluetoothactivity.java
package com.example.thecaseforbluetooth; import java.util.arraylist; import java.util.set; import android.app.activity; 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.os.bundle; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.arrayadapter; import android.widget.button; import android.widget.listview; import android.widget.toast; import android.widget.togglebutton; public class bluetoothactivity extends activity { public button searchbtn;//搜索蓝牙设备 public button exitbtn;//退出应用 public button discoverbtn;//设置可被发现 public togglebutton openbtn;//开关蓝牙设备 public button serverbtn; public listview listview;//蓝牙设备清单 public arrayadapter<string> adapter; public arraylist<string> list =new arraylist<string>(); private bluetoothadapter bluetoothadapter = bluetoothadapter.getdefaultadapter(); set<bluetoothdevice> bonddevices ; public context context ; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); searchbtn = (button)findviewbyid(r.id.btnsearch); exitbtn = (button)findviewbyid(r.id.btnexit); discoverbtn = (button)findviewbyid(r.id.btndis); openbtn = (togglebutton)findviewbyid(r.id.tbtnswitch); serverbtn = (button)findviewbyid(r.id.btnserver); listview = (listview)findviewbyid(r.id.lvdevices); context = getapplicationcontext(); adapter = new arrayadapter<string>(this, android.r.layout.simple_list_item_1,list); listview.setadapter(adapter); openbtn.setchecked(false); //注册广播接收信号 intentfilter intent = new intentfilter(); intent.addaction(bluetoothdevice.action_found);// 用broadcastreceiver来取得搜索结果 intent.addaction(bluetoothadapter.action_scan_mode_changed); //每当扫描模式变化的时候,应用程序可以为通过action_scan_mode_changed值来监听全局的消息通知。比如,当设备停止被搜寻以后,该消息可以被系统通知給应用程序。 intent.addaction(bluetoothadapter.action_state_changed); //每当蓝牙模块被打开或者关闭,应用程序可以为通过action_state_changed值来监听全局的消息通知。 registerreceiver(searchreceiver, intent); //显示已配对设备以及搜索未配对设备 searchbtn.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub if(bluetoothadapter.isdiscovering()){ bluetoothadapter.canceldiscovery(); } list.clear(); bonddevices = bluetoothadapter.getbondeddevices(); for(bluetoothdevice device : bonddevices) { string str = " 已配对完成 " + device.getname() +" " + device.getaddress(); list.add(str); adapter.notifydatasetchanged(); } bluetoothadapter.startdiscovery(); } }); //退出应用 exitbtn.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub bluetoothactivity.this.finish(); } }); //设置蓝牙设备可发现 discoverbtn.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub intent discoverintent = new intent(bluetoothadapter.action_request_discoverable); discoverintent.putextra(bluetoothadapter.extra_discoverable_duration, 300); startactivity(discoverintent); } }); //开关蓝牙设备 openbtn.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub if(openbtn.ischecked() == true){ bluetoothadapter.disable(); } else if(openbtn.ischecked() == false){ bluetoothadapter.enable(); } } }); //作为服务端开启 serverbtn.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub serverthread serverthread = new serverthread(bluetoothadapter, context); toast.maketext(context, "server 端启动", 5000).show(); serverthread.start(); } }); listview.setonitemclicklistener(new itemclicklistener()); } @override public void onstart() { super.onstart(); // if bt is not on, request that it be enabled. if(bluetoothadapter == null){ toast.maketext(context, "蓝牙设备不可用", 5000).show(); } if (!bluetoothadapter.isenabled()) { intent enableintent = new intent( bluetoothadapter.action_request_enable); startactivityforresult(enableintent, 3); } } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; } private final broadcastreceiver searchreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { // todo auto-generated method stub string action = intent.getaction(); bluetoothdevice device = null; if(bluetoothdevice.action_found.equals(action)){ device = intent.getparcelableextra(bluetoothdevice.extra_device); if (device.getbondstate() == bluetoothdevice.bond_none) { toast.maketext(context, device.getname()+"", 5000).show(); string str = " 未配对完成 " + device.getname() +" " + device.getaddress(); if (list.indexof(str) == -1)// 防止重复添加 list.add(str); } adapter.notifydatasetchanged(); } } }; public class itemclicklistener implements onitemclicklistener { @override public void onitemclick(adapterview<?> arg0, view arg1, int arg2, long arg3) { // todo auto-generated method stub if(bluetoothadapter.isdiscovering()) bluetoothadapter.canceldiscovery(); string str = list.get(arg2); string address = str.substring(str.length() - 17); bluetoothdevice btdev = bluetoothadapter.getremotedevice(address); clientthread clientthread = new clientthread(btdev, context); clientthread.start(); }} }
bluetoothprotocol.java
package com.example.thecaseforbluetooth; public interface bluetoothprotocol { public static final string protocol_scheme_l2cap = "btl2cap"; public static final string protocol_scheme_rfcomm = "btspp"; public static final string protocol_scheme_bt_obex = "btgoep"; public static final string protocol_scheme_tcp_obex = "tcpobex"; }
serverthread.java
package com.example.thecaseforbluetooth; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.uuid; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothserversocket; import android.bluetooth.bluetoothsocket; import android.content.context; import android.os.message; import android.util.log; import android.widget.toast; public class serverthread extends thread { public bluetoothserversocket mserversocket; public bluetoothadapter bluetoothadapter; public bluetoothsocket socket; public context context; public serverthread(bluetoothadapter bluetoothadapter,context context) { this.bluetoothadapter = bluetoothadapter; this.context = context; } public void run() { try { /* 创建一个蓝牙服务器 * 参数分别:服务器名称、uuid */ mserversocket = bluetoothadapter.listenusingrfcommwithservicerecord(bluetoothprotocol.protocol_scheme_rfcomm, uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb")); // /* 接受客户端的连接请求 */ socket = mserversocket.accept(); //下面代码作者偷懒,读写另外起一个线程最好 //接收数据 byte[] buffer = new byte[1024]; int bytes; inputstream mminstream = null; try { mminstream = socket.getinputstream(); } catch (ioexception e1) { // todo auto-generated catch block e1.printstacktrace(); } system.out.println("zhoulc server"); while(true){ if( (bytes = mminstream.read(buffer)) > 0 ) { byte[] buf_data = new byte[bytes]; for(int i=0; i<bytes; i++) { buf_data[i] = buffer[i]; } string s = new string(buf_data); system.out.println(s+"zhoulc server is in"); } } } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } }
clientthread.java
package com.example.thecaseforbluetooth; import java.io.ioexception; import java.io.outputstream; import java.util.uuid; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothsocket; import android.content.context; import android.widget.toast; public class clientthread extends thread { public bluetoothsocket socket; public bluetoothdevice device; public context context; public clientthread(bluetoothdevice device,context context){ this.device = device; this.context = context; } public void run() { try { //创建一个socket连接:只需要服务器在注册时的uuid号 socket = device.createrfcommsockettoservicerecord(uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb")); //连接 socket.connect(); //下面代码作者偷懒,读写另外起一个线程最好 //发送数据 if (socket == null) { toast.maketext(context, "链接失败", 5000).show(); return; } system.out.println("zhoulc client"); while(true){ try { system.out.println("zhoulc client is in"); string msg = "hello everybody i am client"; outputstream os = socket.getoutputstream(); os.write(msg.getbytes()); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } catch (ioexception e) { e.printstacktrace(); } } }
蓝牙设备之间自动配对
1、蓝牙设备之间自动配对,需要两个设备都安装进行配对的apk(网上好多自动配对的帖子都没有说明情况)
2、在自动匹配的时候想通过反射调用bluetoothdevice的setpin、createbond、cancelpairinguserinput实现设置密钥、配对请求创建、取消密钥信息输入等。
1)createbond()创建,最终会调到源码的bluetoothservice的createbond(string address)方法,通过对源码浅显的了解,createbond主要是写入匹配密钥(bluetoothservice的writedockpin())以及进入jni注册回调函数oncreatepaireddeviceresult观察匹配结果
比如: // pins did not match, or remote device did not respond to pin
// request in time
// we rejected pairing, or the remote side rejected pairing. this
// happens if either side presses 'cancel' at the pairing dialog.
// not sure if this happens
// other device is not responding at all
// already bonded
等,在jni中创建了进行匹配的device("createpaireddevice"),这时bluetooth会发送一个action_pairing_request的广播,只有当前会出现密钥框的蓝牙设备收到。写完密钥之后,发送广播给另外一个蓝牙设备接收,然后打开密钥输入框进行匹配。
2)setpin()设置密钥,通过查看setting源码,发现在确认输入密钥之后会调用setpin()(如果点取消,就会调用cancelpairinguserinput,取消密钥框),setpin具体通过d-bus做了什么没有去深究,但是在调用setpin的时候会remove掉一个map里面的键值对(address:int),也就是我们在调用setpin之后如果再去调用oncreatepaireddeviceresult,则该方法一定返回false,并且出现下面的打印提示:canceluserinputnative(b8:ff:fe:55:ef:d6) called but no native data available, ignoring. maybe the passkeyagent request was already cancelled by the remote or by bluez.(因为该方法也会remove掉一个键值对)
3)cancelpairinguserinput()取消用户输入密钥框,个人觉得一般情况下不要和setpin(setpasskey、setpairingconfirmation、setremoteoutofbanddata)一起用,这几个方法都会remove掉map里面的key:value(也就是互斥的)。
3、蓝牙耳机、手柄等一些无法手动配置的设备是如何完成自动配对的。
在源码里面有一个自动配对的方法,也就是把pin值自动设为“0000”
/*package*/ synchronized boolean attemptautopair(string address) {
if (!mbondstate.hasautopairingfailed(address) &&
!mbondstate.isautopairingblacklisted(address)) {
mbondstate.attempt(address);
setpin(address, bluetoothdevice.convertpintobytes("0000"));
return true;
}
return false;
}
该方法是在底层回调到java层的onrequestpincode方法时被调用,首先 check if its a dock(正常输入的密钥,走正常配对方式,双方输入匹配值),然后再 try 0000 once if the device looks dumb(涉及到device.audio_video相关部分如:耳机,免提等进入自动匹配模式)进行自动配对。
言归正传,虽然个人觉得自动配对需要双方乃至多方蓝牙设备都需要装上实现自动配对的apk,已经失去了自动配对的意义,但有可能还是会派上用场。下面我们看看现实情况的自动配对是什么样的吧。
由于bluetoothdevice配对的方法都是hide的,所以我们需要通过反射调用被隐藏的方法,现在基本都是通用的工具类型了,网上模式基本一样。
clsutils.java
package cn.bluetooth; import java.lang.reflect.field; import java.lang.reflect.method; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.util.log; public class clsutils { public static bluetoothdevice remotedevice=null; /** * 与设备配对 参考源码:platform/packages/apps/settings.git * /settings/src/com/android/settings/bluetooth/cachedbluetoothdevice.java */ @suppresswarnings("unchecked") static public boolean createbond(@suppresswarnings("rawtypes") class btclass, bluetoothdevice btdevice) throws exception { method createbondmethod = btclass.getmethod("createbond"); boolean returnvalue = (boolean) createbondmethod.invoke(btdevice); return returnvalue.booleanvalue(); } /** * 与设备解除配对 参考源码:platform/packages/apps/settings.git * /settings/src/com/android/settings/bluetooth/cachedbluetoothdevice.java */ @suppresswarnings("unchecked") static public boolean removebond(class btclass, bluetoothdevice btdevice) throws exception { method removebondmethod = btclass.getmethod("removebond"); boolean returnvalue = (boolean) removebondmethod.invoke(btdevice); return returnvalue.booleanvalue(); } @suppresswarnings("unchecked") static public boolean setpin(class btclass, bluetoothdevice btdevice, string str) throws exception { try { method removebondmethod = btclass.getdeclaredmethod("setpin", new class[] {byte[].class}); boolean returnvalue = (boolean) removebondmethod.invoke(btdevice, new object[] {str.getbytes()}); log.d("returnvalue", "setpin is success " +btdevice.getaddress()+ returnvalue.booleanvalue()); } catch (securityexception e) { // throw new runtimeexception(e.getmessage()); e.printstacktrace(); } catch (illegalargumentexception e) { // throw new runtimeexception(e.getmessage()); e.printstacktrace(); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } return true; } // 取消用户输入 @suppresswarnings("unchecked") static public boolean cancelpairinguserinput(class btclass, bluetoothdevice device) throws exception { method createbondmethod = btclass.getmethod("cancelpairinguserinput"); // cancelbondprocess() boolean returnvalue = (boolean) createbondmethod.invoke(device); log.d("returnvalue", "cancelpairinguserinput is success " + returnvalue.booleanvalue()); return returnvalue.booleanvalue(); } // 取消配对 @suppresswarnings("unchecked") static public boolean cancelbondprocess(class btclass, bluetoothdevice device) throws exception { method createbondmethod = btclass.getmethod("cancelbondprocess"); boolean returnvalue = (boolean) createbondmethod.invoke(device); return returnvalue.booleanvalue(); } /** * * @param clsshow */ @suppresswarnings("unchecked") static public void printallinform(class clsshow) { try { // 取得所有方法 method[] hidemethod = clsshow.getmethods(); int i = 0; for (; i < hidemethod.length; i++) { //log.e("method name", hidemethod.getname() + ";and the i is:" // + i); } // 取得所有常量 field[] allfields = clsshow.getfields(); for (i = 0; i < allfields.length; i++) { //log.e("field name", allfields.getname()); } } catch (securityexception e) { // throw new runtimeexception(e.getmessage()); e.printstacktrace(); } catch (illegalargumentexception e) { // throw new runtimeexception(e.getmessage()); e.printstacktrace(); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } }
bluetooth1.java 主activity,所有界面操作实现地方
package cn.bluetooth; import java.io.ioexception; import java.util.arraylist; import java.util.list; import android.app.activity; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothsocket; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.bundle; import android.util.log; import android.view.menu; import android.view.view; import android.widget.adapterview; import android.widget.arrayadapter; import android.widget.button; import android.widget.listview; import android.widget.toast; import android.widget.togglebutton; public class bluetooth1 extends activity { /** called when the activity is first created. */ button btnsearch, btndis, btnexit; togglebutton tbtnswitch; listview lvbtdevices; arrayadapter<string> adtdevices; list<string> lstdevices = new arraylist<string>(); bluetoothadapter btadapt; public static bluetoothsocket btsocket; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); // button 设置 btnsearch = (button) this.findviewbyid(r.id.btnsearch); btnsearch.setonclicklistener(new clickevent()); btnexit = (button) this.findviewbyid(r.id.btnexit); btnexit.setonclicklistener(new clickevent()); btndis = (button) this.findviewbyid(r.id.btndis); btndis.setonclicklistener(new clickevent()); // tooglebutton设置 tbtnswitch = (togglebutton) this.findviewbyid(r.id.tbtnswitch); tbtnswitch.setonclicklistener(new clickevent()); // listview及其数据源 适配器 lvbtdevices = (listview) this.findviewbyid(r.id.lvdevices); adtdevices = new arrayadapter<string>(this, android.r.layout.simple_list_item_1, lstdevices); lvbtdevices.setadapter(adtdevices); lvbtdevices.setonitemclicklistener(new itemclickevent()); btadapt = bluetoothadapter.getdefaultadapter();// 初始化本机蓝牙功能 // ======================================================== // modified by wiley /* * if (btadapt.getstate() == bluetoothadapter.state_off)// 读取蓝牙状态并显示 * tbtnswitch.setchecked(false); else if (btadapt.getstate() == * bluetoothadapter.state_on) tbtnswitch.setchecked(true); */ if (btadapt.isenabled()) { tbtnswitch.setchecked(false); } else { tbtnswitch.setchecked(true); } // ============================================================ // 注册receiver来获取蓝牙设备相关的结果 intentfilter intent = new intentfilter(); intent.addaction(bluetoothdevice.action_found);// 用broadcastreceiver来取得搜索结果 intent.addaction(bluetoothdevice.action_bond_state_changed); intent.addaction(bluetoothadapter.action_scan_mode_changed); intent.addaction(bluetoothadapter.action_state_changed); registerreceiver(searchdevices, intent); } private final broadcastreceiver searchdevices = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { string action = intent.getaction(); bundle b = intent.getextras(); object[] lstname = b.keyset().toarray(); // 显示所有收到的消息及其细节 for (int i = 0; i < lstname.length; i++) { string keyname = lstname.tostring(); log.e(keyname, string.valueof(b.get(keyname))); } bluetoothdevice device = null; // 搜索设备时,取得设备的mac地址 if (bluetoothdevice.action_found.equals(action)) { device = intent.getparcelableextra(bluetoothdevice.extra_device); if (device.getbondstate() == bluetoothdevice.bond_none) { string str = " 未配对|" + device.getname() + "|" + device.getaddress(); if (lstdevices.indexof(str) == -1)// 防止重复添加 lstdevices.add(str); // 获取设备名称和mac地址 adtdevices.notifydatasetchanged(); } }else if(bluetoothdevice.action_bond_state_changed.equals(action)){ device = intent.getparcelableextra(bluetoothdevice.extra_device); switch (device.getbondstate()) { case bluetoothdevice.bond_bonding: log.d("bluetoothtestactivity", "正在配对......"); break; case bluetoothdevice.bond_bonded: log.d("bluetoothtestactivity", "完成配对"); //connect(device);//连接设备 break; case bluetoothdevice.bond_none: log.d("bluetoothtestactivity", "取消配对"); default: break; } } } }; @override protected void ondestroy() { this.unregisterreceiver(searchdevices); super.ondestroy(); android.os.process.killprocess(android.os.process.mypid()); } class itemclickevent implements adapterview.onitemclicklistener { @override public void onitemclick(adapterview<?> arg0, view arg1, int arg2, long arg3) { if(btadapt.isdiscovering())btadapt.canceldiscovery(); string str = lstdevices.get(arg2); string[] values = str.split("\\|"); string address = values[2]; log.e("address", values[2]); bluetoothdevice btdev = btadapt.getremotedevice(address); try { boolean returnvalue = false; if (btdev.getbondstate() == bluetoothdevice.bond_none) { toast.maketext(bluetooth1.this, "远程设备发送蓝牙配对请求", 5000).show(); //这里只需要createbond就行了 clsutils.createbond(btdev.getclass(), btdev); }else if(btdev.getbondstate() == bluetoothdevice.bond_bonded){ toast.maketext(bluetooth1.this, btdev.getbondstate()+" ....正在连接..", 1000).show(); } } catch (exception e) { e.printstacktrace(); } } } class clickevent implements view.onclicklistener { @override public void onclick(view v) { if (v == btnsearch)// 搜索蓝牙设备,在broadcastreceiver显示结果 { if (btadapt.getstate() == bluetoothadapter.state_off) {// 如果蓝牙还没开启 toast.maketext(bluetooth1.this, "请先打开蓝牙", 1000) .show(); return; } if (btadapt.isdiscovering()) btadapt.canceldiscovery(); lstdevices.clear(); object[] lstdevice = btadapt.getbondeddevices().toarray(); for (int i = 0; i < lstdevice.length; i++) { bluetoothdevice device = (bluetoothdevice) lstdevice[i]; string str = " 已配对|" + device.getname() + "|" + device.getaddress(); lstdevices.add(str); // 获取设备名称和mac地址 adtdevices.notifydatasetchanged(); } settitle("本机:" + btadapt.getaddress()); btadapt.startdiscovery(); } else if (v == tbtnswitch) {// 本机蓝牙启动/关闭 if (tbtnswitch.ischecked() == false) btadapt.enable(); else if (tbtnswitch.ischecked() == true) btadapt.disable(); } else if (v == btndis)// 本机可以被搜索 { intent discoverableintent = new intent( bluetoothadapter.action_request_discoverable); discoverableintent.putextra( bluetoothadapter.extra_discoverable_duration, 300); startactivity(discoverableintent); } else if (v == btnexit) { try { if (btsocket != null) btsocket.close(); } catch (ioexception e) { e.printstacktrace(); } bluetooth1.this.finish(); } } } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.main, menu); return true; } }
pairingrequest.java (重要部分,自动配对主要是这个部分完成,activity只是创建了一个配对请求)
package cn.bluetooth; import android.bluetooth.bluetoothdevice; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.widget.toast; public class pairingrequest extends broadcastreceiver { string strpsw = "0000"; final string action_pairing_request = "android.bluetooth.device.action.pairing_request"; static bluetoothdevice remotedevice = null; @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(action_pairing_request)) { bluetoothdevice device = intent .getparcelableextra(bluetoothdevice.extra_device); if (device.getbondstate() != bluetoothdevice.bond_bonded) { try { clsutils.setpin(device.getclass(), device, strpsw); // 手机和蓝牙采集器配对 // clsutils.cancelpairinguserinput(device.getclass(), // device); //一般调用不成功,前言里面讲解过了 toast.maketext(context, "配对信息" + device.getname(), 5000) .show(); } catch (exception e) { // todo auto-generated catch block toast.maketext(context, "请求连接错误...", 1000).show(); } } // */ // pair(device.getaddress(),strpsw); } } }
androidmanifest.xml 启动activity,接收广播
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.bluetooth" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="15" /> <uses-permission android:name="android.permission.bluetooth_admin" /> <uses-permission android:name="android.permission.bluetooth" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <activity android:name=".bluetooth1" android:label="@string/title_activity_bluetooth1" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <receiver android:name=".pairingrequest"> <intent-filter> <action android:name="android.bluetooth.device.action.pairing_request" /> </intent-filter> </receiver> </application> </manifest>
main.xml 布局
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearlayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnsearch" android:text="btnsearch" /> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnexit" android:text="btnexit" /> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btndis" android:text="btndis" /> <togglebutton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tbtnswitch" android:text="tbtnswitch" /> <listview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/lvdevices" /> </linearlayout>