我的编程空间,编程开发者的网络收藏夹
学习永远不晚

Android蓝牙通信编程

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

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()) {
 
 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;
 
 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;
 
 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码

您可能感兴趣的文章:Android蓝牙开发深入解析android实现蓝牙文件发送的实例代码,支持多种机型Android Bluetooth蓝牙技术使用流程详解Android编程之蓝牙测试实例Android单片机与蓝牙模块通信实例代码Android提高之蓝牙传感应用实例Android系统中的蓝牙连接程序编写实例教程Android 蓝牙2.0的使用方法详解Android开发中编写蓝牙相关功能的核心代码讲解Android蓝牙通信聊天实现发送和接受功能Android设备间实现蓝牙(Bluetooth)共享上网Android 蓝牙开发实例解析Android实现的简单蓝牙程序示例


免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

Android蓝牙通信编程

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

Android蓝牙通信编程

项目涉及蓝牙通信,所以就简单的学了学,下面是自己参考了一些资料后的总结,希望对大家有帮助。 以下是开发中的几个关键步骤: 1、首先开启蓝牙 2、搜索可用设备 3、创建蓝牙socket,获取输入输出流 4、读取和写入数据 5、断开连接
2022-06-06

Android蓝牙通信方式有哪些

Android蓝牙通信方式有以下几种:基本数据包交换(Basic Rate/Enhanced Data Rate, BR/EDR):这是最常用的蓝牙通信方式,用于传输音频、文件和其他数据。它支持点对点和广播通信。低能耗蓝牙(Low Ener
2023-10-24

Android中怎么实现蓝牙通信

这期内容当中小编将会给大家带来有关Android中怎么实现蓝牙通信,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。一:注意事项 1:android6.0使用蓝牙时,需要开启gps定位权限,不然无法
2023-05-30

Android编程之蓝牙测试实例

本文实例讲述了Android编程之蓝牙测试。分享给大家供大家参考。具体分析如下: 一、软件平台: win7 + eclipse + sdk 二、设计思路: 配合倒计时定时器实现蓝牙打开,可见,扫描三个功能 三、源代码: main.xml:<
2022-06-06

Android Phone蓝牙通信方式总结(Socket与Gatt)

Android手机间通过蓝牙方式进行通信,有两种常见的方式,一种是socket方式,另一种是通过Gatt Server(Android 5.0以后)通信,socket方式最为简单,但是很多低功耗的蓝牙设备,如单片机上的蓝牙模块可能不支持。而
2022-06-06

Android单片机与蓝牙模块通信实例代码

啦啦毕业了,毕业前要写毕业设计,需要写一个简单的蓝牙APP进行交互,通过参考网上资料,问题顺利搞定,下面小编把具体实现思路分享给大家,供大家参考。 1、Android蓝牙编程蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码
2022-06-06

Android BLE蓝牙开发流程

Android BLE蓝牙开发流程包括以下步骤:1. 检查设备是否支持BLE:使用`BluetoothAdapter`类的`getDefaultAdapter()`方法来获取`BluetoothAdapter`对象,然后使用`isMulti
2023-09-20

Android蓝牙通信聊天实现发送和接受功能

很不错的蓝牙通信demo实现发送和接受功能,就用了两个类就实现了,具体内容如下 说下思路把 主要有两个类 主界面类 和 蓝牙聊天服务类 。 首先创建线程 实际上就是创建BluetoothChatService() (蓝牙聊天服务类) 这个时
2022-06-06

Android 9.0 蓝牙配对流程

1 、UI DeviceListPreferenceFragment是蓝牙扫描到的设备列表,点击其中一个蓝牙设备,调用onPreferenceTreeClick方法开始蓝牙的配对过程。 /packages/apps/Settings/src
2022-06-06

Android适配安卓6.0蓝牙通讯实现过程

事先说明: 安卓蓝牙需要定位权限申请,在安卓6.0需要用户手动确认权限后才能使用,各位可以自行查询资料实现,如果嫌麻烦,可以用第三方Bmob集成好的工具类进行实现,详细可以看http://blog.csdn.net/qq_30379689/
2022-06-06

Android实现蓝牙客户端与服务器端通信示例

一、首先说明:蓝牙通信必须用手机测试,因为avd里没有相关的硬件,会报错! 好了,看看最后的效果图: 二、概述: 1.判断是否支持BluetoothBluetoothAdapter bluetoothAdapter = Bluetoot
2022-06-06

Android系统中的蓝牙连接程序编写实例教程

Bluetooth结构 1、JAVA层 frameworks/base/core/java/android/bluetooth/ 包含了bluetooth的JAVA类。 2、JNI层 frameworks/base/core/jni/and
2022-06-06

蓝牙聊天App设计1:Android Studio制作蓝牙聊天通讯软件(UI界面设计)

前言:蓝牙聊天App设计全部有三篇文章(一、UI界面设计,二、蓝牙搜索配对连接实现,三、蓝牙连接聊天),这篇文章是一、UI界面设计 课程1:Android Studio小白安装教程,以及第一个Android项目案例“Hello World”
2023-08-16

Android实现的简单蓝牙程序示例

本文实例讲述了Android实现的简单蓝牙程序。分享给大家供大家参考,具体如下: 我将在这篇文章中介绍了的Android蓝牙程序。这个程序就是将实现把手机变做电脑PPT播放的遥控器:用音量加和音量减键来控制PPT页面的切换。 遥控器服务器端
2022-06-06

编程热搜

  • Android:VolumeShaper
    VolumeShaper(支持版本改一下,minsdkversion:26,android8.0(api26)进一步学习对声音的编辑,可以让音频的声音有变化的播放 VolumeShaper.Configuration的三个参数 durati
    Android:VolumeShaper
  • Android崩溃异常捕获方法
    开发中最让人头疼的是应用突然爆炸,然后跳回到桌面。而且我们常常不知道这种状况会何时出现,在应用调试阶段还好,还可以通过调试工具的日志查看错误出现在哪里。但平时使用的时候给你闹崩溃,那你就欲哭无泪了。 那么今天主要讲一下如何去捕捉系统出现的U
    Android崩溃异常捕获方法
  • android开发教程之获取power_profile.xml文件的方法(android运行时能耗值)
    系统的设置–>电池–>使用情况中,统计的能耗的使用情况也是以power_profile.xml的value作为基础参数的1、我的手机中power_profile.xml的内容: HTC t328w代码如下:
    android开发教程之获取power_profile.xml文件的方法(android运行时能耗值)
  • Android SQLite数据库基本操作方法
    程序的最主要的功能在于对数据进行操作,通过对数据进行操作来实现某个功能。而数据库就是很重要的一个方面的,Android中内置了小巧轻便,功能却很强的一个数据库–SQLite数据库。那么就来看一下在Android程序中怎么去操作SQLite数
    Android SQLite数据库基本操作方法
  • ubuntu21.04怎么创建桌面快捷图标?ubuntu软件放到桌面的技巧
    工作的时候为了方便直接打开编辑文件,一些常用的软件或者文件我们会放在桌面,但是在ubuntu20.04下直接直接拖拽文件到桌面根本没有效果,在进入桌面后发现软件列表中的软件只能收藏到面板,无法复制到桌面使用,不知道为什么会这样,似乎并不是很
    ubuntu21.04怎么创建桌面快捷图标?ubuntu软件放到桌面的技巧
  • android获取当前手机号示例程序
    代码如下: public String getLocalNumber() { TelephonyManager tManager =
    android获取当前手机号示例程序
  • Android音视频开发(三)TextureView
    简介 TextureView与SurfaceView类似,可用于显示视频或OpenGL场景。 与SurfaceView的区别 SurfaceView不能使用变换和缩放等操作,不能叠加(Overlay)两个SurfaceView。 Textu
    Android音视频开发(三)TextureView
  • android获取屏幕高度和宽度的实现方法
    本文实例讲述了android获取屏幕高度和宽度的实现方法。分享给大家供大家参考。具体分析如下: 我们需要获取Android手机或Pad的屏幕的物理尺寸,以便于界面的设计或是其他功能的实现。下面就介绍讲一讲如何获取屏幕的物理尺寸 下面的代码即
    android获取屏幕高度和宽度的实现方法
  • Android自定义popupwindow实例代码
    先来看看效果图:一、布局
  • Android第一次实验
    一、实验原理 1.1实验目标 编程实现用户名与密码的存储与调用。 1.2实验要求 设计用户登录界面、登录成功界面、用户注册界面,用户注册时,将其用户名、密码保存到SharedPreference中,登录时输入用户名、密码,读取SharedP
    Android第一次实验

目录