项目涉及蓝牙通信,所以就简单的学了学,下面是自己参考了一些资料后的总结,希望对大家有帮助。
以下是开发中的几个关键步骤:
1、首先开启蓝牙
2、搜索可用设备
3、创建蓝牙socket,获取输入输出流
4、读取和写入数据
5、断开连接关闭蓝牙 @H_404_7@
下面是一个蓝牙聊天demo
效果图: @H_404_7@
@H_404_7@@H_404_7@
在使用蓝牙是 BluetoothAdapter 对蓝牙开启,关闭,获取设备列表,发现设备,搜索等核心功能 @H_404_7@
下面对它进行封装:
@H_404_7@
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@H_404_7@
server功能类封装:
@H_404_7@
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,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功能封装:@H_404_7@
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,"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(); } } }
聊天界面,使用上面分装好的类,处理信息 @H_404_7@
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界面:@H_404_7@
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);// 定义一个d出框对象 dialog.setTitle("Confirmed connecting device"); dialog.setMessage(item.getBuletoothname()); dialog.setPositivebutton("connect",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",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:@H_404_7@
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:@H_404_7@
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; } }
使用到的辅助类:@H_404_7@
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"/>@H_404_7@
在编程中遇到的问题:
Exception: Unable to start Service discovery
java.io.IOException: Unable to start Service discovery错误
@H_404_7@
1、必须保证客户端,服务器端中的UUID统一,客户端格式为:UUID格式一般是"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
@H_404_7@
例如:UUID.fromString("81403000-13df-b000-7cf4-350b4a2110ee");
2、必须进行配对处理后方可能够连接 @H_404_7@
扩展:蓝牙后台配对实现(网上看到的整理如下)@H_404_7@
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码
@H_404_7@
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。@H_404_7@ 总结
以上是内存溢出为你收集整理的Android蓝牙通信编程全部内容,希望文章能够帮你解决Android蓝牙通信编程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)