Android蓝牙通信编程
项目涉及蓝牙通信,所以就简单的学了学,下面是自己参考了一些资料后的总结,希望对大家有帮助。
以下是开发中的几个关键步骤:
1、首先开启蓝牙
2、搜索可用设备
3、创建蓝牙socket,获取输入输出流
4、读取和写入数据
5、断开连接关闭蓝牙
下面是一个蓝牙聊天demo
效果图:
在使用蓝牙是 bluetoothadapter 对蓝牙开启,关闭,获取设备列表,发现设备,搜索等核心功能
下面对它进行封装:
package com.xiaoyu.bluetooth; import java.util.arraylist; import java.util.iterator; import java.util.list; import java.util.set; import android.app.activity; import android.app.alertdialog; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.content.broadcastreceiver; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.content.intentfilter; public class btmanage { // private list<btitem> mlistdevicebt=null; private bluetoothadapter mbtadapter =null; private static btmanage mag=null; private btmanage(){ // mlistdevicebt=new arraylist<btitem>(); mbtadapter=bluetoothadapter.getdefaultadapter(); } public static btmanage getinstance(){ if(null==mag) mag=new btmanage(); return mag; } private statusbluetooth bluestatuslis=null; public void setbluelistner(statusbluetooth bluelis){ this.bluestatuslis=bluelis; } public bluetoothadapter getbtadapter(){ return this.mbtadapter; } public void openbluetooth(activity activity){ if(null==mbtadapter){ ////device does not support bluetooth alertdialog.builder dialog = new alertdialog.builder(activity); dialog.settitle("no bluetooth devices"); dialog.setmessage("your equipment does not support bluetooth, please change device"); dialog.setnegativebutton("cancel", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { } }); dialog.show(); return; } // if bt is not on, request that it be enabled. if (!mbtadapter.isenabled()) { /*intent enableintent = new intent(bluetoothadapter.action_request_enable); activity.startactivityforresult(enableintent, 3);*/ mbtadapter.enable(); } } public void closebluetooth(){ if(mbtadapter.isenabled()) mbtadapter.disable(); } public boolean isdiscovering(){ return mbtadapter.isdiscovering(); } public void scandevice(){ // mlistdevicebt.clear(); if(!mbtadapter.isdiscovering()) mbtadapter.startdiscovery(); } public void cancelscandevice(){ if(mbtadapter.isdiscovering()) mbtadapter.canceldiscovery(); } public void registerbluetoothreceiver(context mcontext){ // register for broadcasts when start bluetooth search intentfilter startsearchfilter = new intentfilter(bluetoothadapter.action_discovery_started); mcontext.registerreceiver(mbluetoothreceiver, startsearchfilter); // register for broadcasts when a device is discovered intentfilter discoveryfilter = new intentfilter(bluetoothdevice.action_found); mcontext.registerreceiver(mbluetoothreceiver, discoveryfilter); // register for broadcasts when discovery has finished intentfilter foundfilter = new intentfilter(bluetoothadapter.action_discovery_finished); mcontext.registerreceiver(mbluetoothreceiver, foundfilter); } public void unregisterbluetooth(context mcontext){ cancelscandevice(); mcontext.unregisterreceiver(mbluetoothreceiver); } public list<btitem> getpairbluetoothitem(){ list<btitem> mbtitemlist=null; // get a set of currently paired devices set<bluetoothdevice> paireddevices = mbtadapter.getbondeddevices(); iterator<bluetoothdevice> it=paireddevices.iterator(); while(it.hasnext()){ if(mbtitemlist==null) mbtitemlist=new arraylist<btitem>(); bluetoothdevice device=it.next(); btitem item=new btitem(); item.setbuletoothname(device.getname()); item.setbluetoothaddress(device.getaddress()); item.setbluetoothtype(bluetoothdevice.bond_bonded); mbtitemlist.add(item); } return mbtitemlist; } private final broadcastreceiver mbluetoothreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { string action = intent.getaction(); if(bluetoothadapter.action_discovery_started.equals(action)) { if(bluestatuslis!=null) bluestatuslis.btdevicesearchstatus(statusbluetooth.search_start); } else if (bluetoothdevice.action_found.equals(action)){ // when discovery finds a device // get the bluetoothdevice object from the intent bluetoothdevice device = intent.getparcelableextra(bluetoothdevice.extra_device); // if it's already paired, skip it, because it's been listed already if (device.getbondstate() != bluetoothdevice.bond_bonded) { btitem item=new btitem(); item.setbuletoothname(device.getname()); item.setbluetoothaddress(device.getaddress()); item.setbluetoothtype(device.getbondstate()); if(bluestatuslis!=null) bluestatuslis.btsearchfinditem(item); // mlistdevicebt.add(item); } } else if (bluetoothadapter.action_discovery_finished.equals(action)){ // when discovery is finished, change the activity title if(bluestatuslis!=null) bluestatuslis.btdevicesearchstatus(statusbluetooth.search_end); } } }; }
蓝牙开发和socket一致,分为server,client
server功能类封装:
package com.xiaoyu.bluetooth; import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.eofexception; import java.io.ioexception; import java.util.uuid; import com.xiaoyu.utils.threadpool; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothserversocket; import android.bluetooth.bluetoothsocket; import android.os.handler; import android.os.message; public class btserver { /* 一些常量,代表服务器的名称 */ 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"; private bluetoothserversocket btserversocket = null; private bluetoothsocket btsocket = null; private bluetoothadapter mbtadapter =null; private bufferedinputstream bis=null; private bufferedoutputstream bos=null; private handler detectedhandler=null; public btserver(bluetoothadapter mbtadapter,handler detectedhandler){ this.mbtadapter=mbtadapter; this.detectedhandler=detectedhandler; } public void startbtserver() { threadpool.getinstance().excutetask(new runnable() { public void run() { try { btserversocket = mbtadapter.listenusingrfcommwithservicerecord(protocol_scheme_rfcomm, uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb")); message msg = new message(); msg.obj = "请稍候,正在等待客户端的连接..."; msg.what = 0; detectedhandler.sendmessage(msg); btsocket=btserversocket.accept(); message msg2 = new message(); string info = "客户端已经连接上!可以发送信息。"; msg2.obj = info; msg.what = 0; detectedhandler.sendmessage(msg2); receivermessagetask(); } catch(eofexception e){ message msg = new message(); msg.obj = "client has close!"; msg.what = 1; detectedhandler.sendmessage(msg); }catch (ioexception e) { e.printstacktrace(); message msg = new message(); msg.obj = "receiver message error! please make client try again connect!"; msg.what = 1; detectedhandler.sendmessage(msg); } } }); } private void receivermessagetask(){ threadpool.getinstance().excutetask(new runnable() { public void run() { byte[] buffer = new byte[2048]; int totalread; /*inputstream input = null; outputstream output=null;*/ try { bis=new bufferedinputstream(btsocket.getinputstream()); bos=new bufferedoutputstream(btsocket.getoutputstream()); } catch (ioexception e) { e.printstacktrace(); } try { // bytearrayoutputstream arrayoutput=null; while((totalread = bis.read(buffer)) > 0 ){ // arrayoutput=new bytearrayoutputstream(); string txt = new string(buffer, 0, totalread, "utf-8"); message msg = new message(); msg.obj = txt; msg.what = 1; detectedhandler.sendmessage(msg); } } catch (ioexception e) { e.printstacktrace(); } } }); } public boolean sendmsg(string msg){ boolean result=false; if(null==btsocket||bos==null) return false; try { bos.write(msg.getbytes()); bos.flush(); result=true; } catch (ioexception e) { e.printstacktrace(); } return result; } public void closebtserver(){ try{ if(bis!=null) bis.close(); if(bos!=null) bos.close(); if(btserversocket!=null) btserversocket.close(); if(btsocket!=null) btsocket.close(); }catch(ioexception e){ e.printstacktrace(); } } }
client功能封装:
package com.xiaoyu.bluetooth; import java.io.bufferedinputstream; import java.io.bufferedoutputstream; import java.io.eofexception; import java.io.ioexception; import java.util.uuid; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothsocket; import android.os.handler; import android.os.message; import android.util.log; import com.xiaoyu.utils.threadpool; public class btclient { final string tag=getclass().getsimplename(); private bluetoothsocket btsocket = null; private bluetoothdevice btdevice = null; private bufferedinputstream bis=null; private bufferedoutputstream bos=null; private bluetoothadapter mbtadapter =null; private handler detectedhandler=null; public btclient(bluetoothadapter mbtadapter,handler detectedhandler){ this.mbtadapter=mbtadapter; this.detectedhandler=detectedhandler; } public void connectbtserver(string address){ //check address is correct if(bluetoothadapter.checkbluetoothaddress(address)){ btdevice = mbtadapter.getremotedevice(address); threadpool.getinstance().excutetask(new runnable() { public void run() { try { btsocket = btdevice.createrfcommsockettoservicerecord(uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb")); message msg2 = new message(); msg2.obj = "请稍候,正在连接服务器:"+bluetoothmsg.bluetoothaddress; msg2.what = 0; detectedhandler.sendmessage(msg2); btsocket.connect(); message msg = new message(); msg.obj = "已经连接上服务端!可以发送信息。"; msg.what = 0; detectedhandler.sendmessage(msg); receivermessagetask(); } catch (ioexception e) { e.printstacktrace(); log.e(tag, e.getmessage()); message msg = new message(); msg.obj = "连接服务端异常!请检查服务器是否正常,断开连接重新试一试。"; msg.what = 0; detectedhandler.sendmessage(msg); } } }); } } private void receivermessagetask(){ threadpool.getinstance().excutetask(new runnable() { public void run() { byte[] buffer = new byte[2048]; int totalread; /*inputstream input = null; outputstream output=null;*/ try { bis=new bufferedinputstream(btsocket.getinputstream()); bos=new bufferedoutputstream(btsocket.getoutputstream()); } catch (ioexception e) { e.printstacktrace(); } try { // bytearrayoutputstream arrayoutput=null; while((totalread = bis.read(buffer)) > 0 ){ // arrayoutput=new bytearrayoutputstream(); string txt = new string(buffer, 0, totalread, "utf-8"); message msg = new message(); msg.obj = "receiver: "+txt; msg.what = 1; detectedhandler.sendmessage(msg); } } catch(eofexception e){ message msg = new message(); msg.obj = "server has close!"; msg.what = 1; detectedhandler.sendmessage(msg); }catch (ioexception e) { e.printstacktrace(); message msg = new message(); msg.obj = "receiver message error! make sure server is ok,and try again connect!"; msg.what = 1; detectedhandler.sendmessage(msg); } } }); } public boolean sendmsg(string msg){ boolean result=false; if(null==btsocket||bos==null) return false; try { bos.write(msg.getbytes()); bos.flush(); result=true; } catch (ioexception e) { e.printstacktrace(); } return result; } public void closebtclient(){ try{ if(bis!=null) bis.close(); if(bos!=null) bos.close(); if(btsocket!=null) btsocket.close(); }catch(ioexception e){ e.printstacktrace(); } } }
聊天界面,使用上面分装好的类,处理信息
package com.xiaoyu.communication; import java.util.arraylist; import java.util.list; import android.app.activity; import android.content.context; import android.content.intent; import android.os.bundle; import android.os.handler; import android.os.message; import android.text.textutils; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.view.inputmethod.inputmethodmanager; import android.widget.arrayadapter; import android.widget.button; import android.widget.edittext; import android.widget.listview; import android.widget.radiogroup; import android.widget.radiogroup.oncheckedchangelistener; import android.widget.toast; import com.xiaoyu.bluetooth.btclient; import com.xiaoyu.bluetooth.btmanage; import com.xiaoyu.bluetooth.btserver; import com.xiaoyu.bluetooth.bluetoothmsg; public class btchatactivity extends activity { private listview mlistview; private button sendbutton; private button disconnectbutton; private edittext editmsgview; private arrayadapter<string> madapter; private list<string> msglist=new arraylist<string>(); private btclient client; private btserver server; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.bt_chat); initview(); } private handler detectedhandler = new handler(){ public void handlemessage(android.os.message msg) { msglist.add(msg.obj.tostring()); madapter.notifydatasetchanged(); mlistview.setselection(msglist.size() - 1); }; }; private void initview() { madapter=new arrayadapter<string>(this, android.r.layout.simple_list_item_1, msglist); mlistview = (listview) findviewbyid(r.id.list); mlistview.setadapter(madapter); mlistview.setfastscrollenabled(true); editmsgview= (edittext)findviewbyid(r.id.messagetext); editmsgview.clearfocus(); radiogroup group = (radiogroup)this.findviewbyid(r.id.radiogroup); group.setoncheckedchangelistener(new oncheckedchangelistener() { // @override // public void oncheckedchanged(radiogroup arg0, int arg1) { // int radioid = arg0.getcheckedradiobuttonid(); // // } @override public void oncheckedchanged(radiogroup group, int checkedid) { switch(checkedid){ case r.id.radionone: bluetoothmsg.serviceorcilent = bluetoothmsg.serverorcilent.none; if(null!=client){ client.closebtclient(); client=null; } if(null!=server){ server.closebtserver(); server=null; } break; case r.id.radioclient: bluetoothmsg.serviceorcilent = bluetoothmsg.serverorcilent.cilent; intent it=new intent(getapplicationcontext(),btdeviceactivity.class); startactivityforresult(it, 100); break; case r.id.radioserver: bluetoothmsg.serviceorcilent = bluetoothmsg.serverorcilent.service; initconnecter(); break; } } }); sendbutton= (button)findviewbyid(r.id.btn_msg_send); sendbutton.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { string msgtext =editmsgview.gettext().tostring(); if (msgtext.length()>0) { if (bluetoothmsg.serviceorcilent == bluetoothmsg.serverorcilent.cilent){ if(null==client) return; if(client.sendmsg(msgtext)){ message msg = new message(); msg.obj = "send: "+msgtext; msg.what = 1; detectedhandler.sendmessage(msg); }else{ message msg = new message(); msg.obj = "send fail!! "; msg.what = 1; detectedhandler.sendmessage(msg); } } else if (bluetoothmsg.serviceorcilent == bluetoothmsg.serverorcilent.service) { if(null==server) return; if(server.sendmsg(msgtext)){ message msg = new message(); msg.obj = "send: "+msgtext; msg.what = 1; detectedhandler.sendmessage(msg); }else{ message msg = new message(); msg.obj = "send fail!! "; msg.what = 1; detectedhandler.sendmessage(msg); } } editmsgview.settext(""); // editmsgview.clearfocus(); // //close inputmethodmanager // inputmethodmanager imm = (inputmethodmanager)getsystemservice(context.input_method_service); // imm.hidesoftinputfromwindow(editmsgview.getwindowtoken(), 0); }else{ toast.maketext(getapplicationcontext(), "发送内容不能为空!", toast.length_short).show(); } } }); disconnectbutton= (button)findviewbyid(r.id.btn_disconnect); disconnectbutton.setonclicklistener(new onclicklistener() { @override public void onclick(view arg0) { if (bluetoothmsg.serviceorcilent == bluetoothmsg.serverorcilent.cilent){ if(null==client) return; client.closebtclient(); } else if (bluetoothmsg.serviceorcilent == bluetoothmsg.serverorcilent.service) { if(null==server) return; server.closebtserver(); } bluetoothmsg.isopen = false; bluetoothmsg.serviceorcilent=bluetoothmsg.serverorcilent.none; toast.maketext(getapplicationcontext(), "已断开连接!", toast.length_short).show(); } }); } @override protected void onresume() { super.onresume(); if (bluetoothmsg.isopen) { toast.maketext(getapplicationcontext(), "连接已经打开,可以通信。如果要再建立连接,请先断开!", toast.length_short).show(); } } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); if(requestcode==100){ //从设备列表返回 initconnecter(); } } private void initconnecter(){ if (bluetoothmsg.serviceorcilent == bluetoothmsg.serverorcilent.cilent) { string address = bluetoothmsg.bluetoothaddress; if (!textutils.isempty(address)) { if(null==client) client=new btclient(btmanage.getinstance().getbtadapter(), detectedhandler); client.connectbtserver(address); bluetoothmsg.isopen = true; } else { toast.maketext(getapplicationcontext(), "address is empty please choose server address !", toast.length_short).show(); } } else if (bluetoothmsg.serviceorcilent == bluetoothmsg.serverorcilent.service) { if(null==server) server=new btserver(btmanage.getinstance().getbtadapter(), detectedhandler); server.startbtserver(); bluetoothmsg.isopen = true; } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.main, menu); return true; } }
client搜索设备列表,连接选择server界面:
package com.xiaoyu.communication; import java.util.arraylist; import java.util.list; import android.app.activity; import android.app.alertdialog; import android.content.dialoginterface; import android.content.intent; import android.os.bundle; import android.view.view; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.arrayadapter; import android.widget.button; import android.widget.listview; import com.xiaoyu.bluetooth.btitem; import com.xiaoyu.bluetooth.btmanage; import com.xiaoyu.bluetooth.bluetoothmsg; import com.xiaoyu.bluetooth.statusbluetooth; public class btdeviceactivity extends activity implements onitemclicklistener ,view.onclicklistener ,statusbluetooth{ // private list<btitem> mlistdevicebt=new arraylist<btitem>(); private listview devicelistview; private button btserch; private btdeviceadapter adapter; private boolean hasregister=false; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.finddevice); setview(); btmanage.getinstance().setbluelistner(this); } private void setview(){ devicelistview=(listview)findviewbyid(r.id.devicelist); devicelistview.setonitemclicklistener(this); adapter=new btdeviceadapter(getapplicationcontext()); devicelistview.setadapter(adapter); devicelistview.setonitemclicklistener(this); btserch=(button)findviewbyid(r.id.start_seach); btserch.setonclicklistener(this); } @override protected void onstart() { super.onstart(); //注册蓝牙接收广播 if(!hasregister){ hasregister=true; btmanage.getinstance().registerbluetoothreceiver(getapplicationcontext()); } } @override protected void onresume() { // todo auto-generated method stub super.onresume(); } @override protected void onpause() { // todo auto-generated method stub super.onpause(); } @override protected void onstop() { super.onstop(); if(hasregister){ hasregister=false; btmanage.getinstance().unregisterbluetooth(getapplicationcontext()); } } @override protected void ondestroy() { super.ondestroy(); } @override public void onitemclick(adapterview<?> parent, view view, int position, long id) { final btitem item=(btitem)adapter.getitem(position); alertdialog.builder dialog = new alertdialog.builder(this);// 定义一个弹出框对象 dialog.settitle("confirmed connecting device"); dialog.setmessage(item.getbuletoothname()); dialog.setpositivebutton("connect", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { // btserch.settext("repeat search"); btmanage.getinstance().cancelscandevice(); bluetoothmsg.bluetoothaddress=item.getbluetoothaddress(); if(bluetoothmsg.lastbluetoothaddress!=bluetoothmsg.bluetoothaddress){ bluetoothmsg.lastbluetoothaddress=bluetoothmsg.bluetoothaddress; } setresult(100); finish(); } }); dialog.setnegativebutton("cancel", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { bluetoothmsg.bluetoothaddress = null; } }); dialog.show(); } @override public void onclick(view v) { btmanage.getinstance().openbluetooth(this); if(btmanage.getinstance().isdiscovering()){ btmanage.getinstance().cancelscandevice(); btserch.settext("start search"); }else{ btmanage.getinstance().scandevice(); btserch.settext("stop search"); } } @override public void btdevicesearchstatus(int resultcode) { switch(resultcode){ case statusbluetooth.search_start: adapter.cleardata(); adapter.adddatamodel(btmanage.getinstance().getpairbluetoothitem()); break; case statusbluetooth.search_end: break; } } @override public void btsearchfinditem(btitem item) { adapter.adddatamodel(item); } @override public void btconnectstatus(int result) { } }
搜索列表adapter:
package com.xiaoyu.communication; import java.util.arraylist; import java.util.list; import android.content.context; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.baseadapter; import android.widget.textview; import com.xiaoyu.bluetooth.btitem; public class btdeviceadapter extends baseadapter{ private list<btitem> mlistitem=new arraylist<btitem>();; private context mcontext=null; private layoutinflater minflater=null; public btdeviceadapter(context context){ this.mcontext=context; // this.mlistitem=mlistitem; this.minflater=(layoutinflater)context.getsystemservice(context.layout_inflater_service); } void cleardata(){ mlistitem.clear(); } void adddatamodel(list<btitem> itemlist){ if(itemlist==null || itemlist.size()==0) return; mlistitem.addall(itemlist); notifydatasetchanged(); } void adddatamodel(btitem item){ mlistitem.add(item); notifydatasetchanged(); } @override public int getcount() { return mlistitem.size(); } @override public object getitem(int position) { return mlistitem.get(position); } @override public long getitemid(int position) { return position; } @override public view getview(int position, view convertview, viewgroup parent) { viewholder holder=null; if(convertview==null){ holder=new viewholder(); convertview = minflater.inflate(r.layout.device_item_row, null); holder.tv=(textview)convertview.findviewbyid(r.id.itemtext); convertview.settag(holder); }else{ holder=(viewholder)convertview.gettag(); } holder.tv.settext(mlistitem.get(position).getbuletoothname()); return convertview; } class viewholder{ textview tv; } }
列表model:
package com.xiaoyu.bluetooth; public class btitem { private string buletoothname=null; private string bluetoothaddress=null; private int bluetoothtype=-1; public string getbuletoothname() { return buletoothname; } public void setbuletoothname(string buletoothname) { this.buletoothname = buletoothname; } public string getbluetoothaddress() { return bluetoothaddress; } public void setbluetoothaddress(string bluetoothaddress) { this.bluetoothaddress = bluetoothaddress; } public int getbluetoothtype() { return bluetoothtype; } public void setbluetoothtype(int bluetoothtype) { this.bluetoothtype = bluetoothtype; } }
使用到的辅助类:
package com.xiaoyu.bluetooth; public class bluetoothmsg { public enum serverorcilent{ none, service, cilent }; //蓝牙连接方式 public static serverorcilent serviceorcilent = serverorcilent.none; //连接蓝牙地址 public static string bluetoothaddress = null,lastbluetoothaddress=null; //通信线程是否开启 public static boolean isopen = false; } package com.xiaoyu.bluetooth; public interface statusbluetooth { final static int search_start=110; final static int search_end=112; final static int servercreatesuccess=211; final static int servercreatefail=212; final static int clientcreatesuccess=221; final static int clientcreatefail=222; final static int connectlose=231; void btdevicesearchstatus(int resultcode); void btsearchfinditem(btitem item); void btconnectstatus(int result); } package com.xiaoyu.utils; import java.util.concurrent.linkedblockingqueue; import java.util.concurrent.threadfactory; import java.util.concurrent.threadpoolexecutor; import java.util.concurrent.timeunit; import java.util.concurrent.atomic.atomicboolean; import java.util.concurrent.atomic.atomicinteger; public class threadpool { private atomicboolean mstopped = new atomicboolean(boolean.false); private threadpoolexecutor mqueue; private final int coresize=2; private final int maxsize=10; private final int timeout=2; private static threadpool pool=null; private threadpool() { mqueue = new threadpoolexecutor(coresize, maxsize, timeout, timeunit.seconds, new linkedblockingqueue<runnable>(), sthreadfactory); // mqueue.allowcorethreadtimeout(true); } public static threadpool getinstance(){ if(null==pool) pool=new threadpool(); return pool; } public void excutetask(runnable run) { mqueue.execute(run); } public void closethreadpool() { if (!mstopped.get()) { mqueue.shutdownnow(); mstopped.set(boolean.true); } } private static final threadfactory sthreadfactory = new threadfactory() { private final atomicinteger mcount = new atomicinteger(1); @override public thread newthread(runnable r) { return new thread(r, "threadpool #" + mcount.getandincrement()); } }; }
最后别忘了加入权限
<uses-permission android:name="android.permission.bluetooth"/>
<uses-permission android:name="android.permission.bluetooth_admin" />
<uses-permission android:name="android.permission.read_contacts"/>
在编程中遇到的问题:
exception: unable to start service discovery
java.io.ioexception: unable to start service discovery错误
1、必须保证客户端,服务器端中的uuid统一,客户端格式为:uuid格式一般是"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
例如:uuid.fromstring("81403000-13df-b000-7cf4-350b4a2110ee");
2、必须进行配对处理后方可能够连接
扩展:蓝牙后台配对实现(网上看到的整理如下)
static public boolean createbond(class btclass, bluetoothdevice btdevice) throws exception { method createbondmethod = btclass.getmethod("createbond"); log.i("life", "createbondmethod = " + createbondmethod.getname()); boolean returnvalue = (boolean) createbondmethod.invoke(btdevice); return returnvalue.booleanvalue(); } static public boolean setpin(class btclass, bluetoothdevice btdevice, string str) throws exception { boolean returnvalue = null; try { method removebondmethod = btclass.getdeclaredmethod("setpin", new class[] { byte[].class }); returnvalue = (boolean) removebondmethod.invoke(btdevice, new object[] { str.getbytes() }); log.i("life", "returnvalue = " + returnvalue); } 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 returnvalue; } // 取消用户输入 static public boolean cancelpairinguserinput(class btclass, bluetoothdevice device) throws exception { method createbondmethod = btclass.getmethod("cancelpairinguserinput"); // cancelbondprocess() boolean returnvalue = (boolean) createbondmethod.invoke(device); log.i("life", "cancelpairinguserinputreturnvalue = " + returnvalue); return returnvalue.booleanvalue(); }
然后监听蓝牙配对的广播 匹配“android.bluetooth.device.action.pairing_request”这个action
然后调用上面的setpin(mdevice.getclass(), mdevice, "1234"); // 手机和蓝牙采集器配对
createbond(mdevice.getclass(), mdevice);
cancelpairinguserinput(mdevice.getclass(), mdevice);
mdevice是你要去连接的那个蓝牙的对象,1234为配对的pin码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: javaweb实现app扫码登录功能
下一篇: Android 进度条使用详解及示例代码