欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android在类微信程序中实现蓝牙聊天功能的示例代码

程序员文章站 2022-04-09 16:59:35
项目要求1.初次打开程序时右上角标题栏显示“无连接”,点击旁边的按钮选择“我的好友”,进入配对界面;2.选择好友之后,返回主界面,标题栏会显示已连接的手机型号;3.两部手机间可通过蓝牙聊天效果展示项目...

项目要求

1.初次打开程序时右上角标题栏显示“无连接”,点击旁边的按钮选择“我的好友”,进入配对界面;
2.选择好友之后,返回主界面,标题栏会显示已连接的手机型号;
3.两部手机间可通过蓝牙聊天

效果展示

Android在类微信程序中实现蓝牙聊天功能的示例代码
Android在类微信程序中实现蓝牙聊天功能的示例代码

项目结构

Android在类微信程序中实现蓝牙聊天功能的示例代码

主要代码

1.在清单文件中注册权限

<uses-permission android:name="android.permission.bluetooth_admin" />
<uses-permission android:name="android.permission.bluetooth" />

2.在文件res / values / strings.xml里,添加程序运行过程中的状态描述文本及配色代码等

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string name="app_name">蓝牙demo</string> 
 <string name="send">发送</string>
 <string name="not_connected">你没有链接一个设备</string>
 <string name="bt_not_enabled_leaving">蓝牙不可用,离开聊天室</string>
 <string name="title_connecting">链接中...</string>
 <string name="title_connected_to">连接到:</string>
 <string name="title_not_connected">无链接</string> 
 <string name="scanning">蓝牙设备搜索中...</string>
 <string name="select_device">选择一个好友链接</string>
 <string name="none_paired">没有配对好友</string>
 <string name="none_found">附近没有发现好友</string>
 <string name="title_paired_devices">已配对好友</string>
 <string name="title_other_devices">其它可连接好友</string>
 <string name="button_scan">搜索好友</string>
 <string name="connect">我的好友</string>
 <string name="discoverable">设置在线</string>
 <string name="back">退出</string>
 <string name="startvideo">开始聊天</string>
 <string name="stopvideo">结束聊天</string> 
</resources>

用于蓝牙会话的服务组件chatservice.java中有三个内部类:acceptthread(接受新连接)、connectthread(发出连接)和connectedthread (已连接)。

// 创建监听线程,准备接受新连接。使用阻塞方式,调用 bluetoothserversocket.accept()
 private class acceptthread extends thread {
  private final bluetoothserversocket mmserversocket;

  public acceptthread() {
   bluetoothserversocket tmp = null;
   try {
    //使用射频端口(rf comm)监听
    tmp = madapter.listenusingrfcommwithservicerecord(name, my_uuid);
   } catch (ioexception e) {
   }
   mmserversocket = tmp;
  }

  @override
  public void run() {
   setname("acceptthread");
   bluetoothsocket socket = null;
   while (mstate != state_connected) {
    try {
     socket = mmserversocket.accept();
    } catch (ioexception e) {
     break;
    }
    if (socket != null) {
     synchronized (chatservice.this) {
      switch (mstate) {
       case state_listen:
       case state_connecting:
        connected(socket, socket.getremotedevice());
        break;
       case state_none:
       case state_connected:
        try {
         socket.close();
        } catch (ioexception e) {
         e.printstacktrace();
        }
        break;
      }
     }
    }
   }
  }

  public void cancel() {
   try {
    mmserversocket.close();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
 }

 /*
  连接线程,专门用来对外发出连接对方蓝牙的请求和处理流程。
  构造函数里通过 bluetoothdevice.createrfcommsockettoservicerecord() ,
  从待连接的 device 产生 bluetoothsocket. 然后在 run 方法中 connect ,
  成功后调用 bluetoothchatsevice 的 connected() 方法。定义 cancel() 在关闭线程时能够关闭相关socket 。
  */
 private class connectthread extends thread {
  private final bluetoothsocket mmsocket;
  private final bluetoothdevice mmdevice;

  public connectthread(bluetoothdevice device) {
   mmdevice = device;
   bluetoothsocket tmp = null;
   try {
    tmp = device.createrfcommsockettoservicerecord(my_uuid);
   } catch (ioexception e) {
    e.printstacktrace();
   }
   mmsocket = tmp;
  }

  @override
  public void run() {
   setname("connectthread");
   madapter.canceldiscovery();
   try {
    mmsocket.connect();
   } catch (ioexception e) {
    connectionfailed();
    try {
     mmsocket.close();
    } catch (ioexception e2) {
     e.printstacktrace();
    }
    chatservice.this.start();
    return;
   }
   synchronized (chatservice.this) {
    mconnectthread = null;
   }
   connected(mmsocket, mmdevice);
  }

  public void cancel() {
   try {
    mmsocket.close();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
 }

 /*
  双方蓝牙连接后一直运行的线程;构造函数中设置输入输出流。
  run()方法中使用阻塞模式的 inputstream.read()循环读取输入流,然后发送到 ui 线程中更新聊天消息。
  本线程也提供了 write() 将聊天消息写入输出流传输至对方,传输成功后回写入 ui 线程。最后使用cancel()关闭连接的 socket
  */
 private class connectedthread extends thread {
  private final bluetoothsocket mmsocket;
  private final inputstream mminstream;
  private final outputstream mmoutstream;

  public connectedthread(bluetoothsocket socket) {
   mmsocket = socket;
   inputstream tmpin = null;
   outputstream tmpout = null;
   try {
    tmpin = socket.getinputstream();
    tmpout = socket.getoutputstream();
   } catch (ioexception e) {
    e.printstacktrace();
   }
   mminstream = tmpin;
   mmoutstream = tmpout;
  }

  @override
  public void run() {
   byte[] buffer = new byte[1024];
   int bytes;
   while (true) {
    try {
     bytes = mminstream.read(buffer);
     mhandler.obtainmessage(weixinfragment.message_read, bytes, -1, buffer).sendtotarget();
    } catch (ioexception e) {
     connectionlost();
     break;
    }
   }
  }

  public void write(byte[] buffer) {
   try {
    mmoutstream.write(buffer);
    mhandler.obtainmessage(weixinfragment.message_write, -1, -1, buffer).sendtotarget();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }

  public void cancel() {
   try {
    mmsocket.close();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
 }

新建activity组件devicelist,实现拾取与之会话的蓝牙设备。本程序供菜单项主界面的选项菜单“我的友好”调用,用于:

(1)显示已配对的好友列表;
(2)搜索可配对的好友进行配对
(3)新选择并配对的蓝牙设备将刷新好友列表

注意:发现新的蓝牙设备并请求配对时,需要对应接受

关键技术:动态注册一个广播接收者,处理蓝牙设备扫描的结果

public class devicelist extends activity{
  private bluetoothadapter mbtadapter;
  private arrayadapter<string> mpaireddevicesarrayadapter;
  private arrayadapter<string> mnewdevicesarrayadapter;
  public static string extra_device_address = "device_address"; //mac地址
  //定义广播接收者,用于处理扫描蓝牙设备后的结果
  private final broadcastreceiver mreceiver = new broadcastreceiver() {
   @override
   public void onreceive(context context, intent intent) {
    string action = intent.getaction();
    if (bluetoothdevice.action_found.equals(action)) {
     bluetoothdevice device = intent.getparcelableextra(bluetoothdevice.extra_device);
     if (device.getbondstate() != bluetoothdevice.bond_bonded) {
      mnewdevicesarrayadapter.add(device.getname() + "\n" + device.getaddress());
     }
    } else if (bluetoothadapter.action_discovery_finished.equals(action)) {
     if (mnewdevicesarrayadapter.getcount() == 0) {
      string nodevices = getresources().gettext(r.string.none_found).tostring();
      mnewdevicesarrayadapter.add(nodevices);
     }
    }
   }
  };
  @override
  protected void oncreate(bundle savedinstancestate) {
   super.oncreate(savedinstancestate);
   setcontentview(r.layout.device_list);
   //在被调用活动里,设置返回结果码
   setresult(activity.result_canceled);
   init(); //活动界面
  }
  private void init() {
   button scanbutton = findviewbyid(r.id.button_scan);
   scanbutton.setonclicklistener(new onclicklistener() {
    public void onclick(view v) {
     toast.maketext(devicelist.this, r.string.scanning, toast.length_long).show();
     dodiscovery(); //搜索蓝牙设备
    }
   });
   mpaireddevicesarrayadapter = new arrayadapter<string>(this, r.layout.device_name);
   mnewdevicesarrayadapter = new arrayadapter<string>(this, r.layout.device_name);
   //已配对蓝牙设备列表
   listview pairedlistview =findviewbyid(r.id.paired_devices);
   pairedlistview.setadapter(mpaireddevicesarrayadapter);
   pairedlistview.setonitemclicklistener(mpairedeviceclicklistener);
   //未配对蓝牙设备列表
   listview newdeviceslistview = findviewbyid(r.id.new_devices);
   newdeviceslistview.setadapter(mnewdevicesarrayadapter);
   newdeviceslistview.setonitemclicklistener(mnewdeviceclicklistener);
   //动态注册广播接收者
   intentfilter filter = new intentfilter(bluetoothdevice.action_found);
   registerreceiver(mreceiver, filter);
   filter = new intentfilter(bluetoothadapter.action_discovery_finished);
   registerreceiver(mreceiver, filter);
   mbtadapter = bluetoothadapter.getdefaultadapter();
   set<bluetoothdevice> paireddevices = mbtadapter.getbondeddevices();
   if (paireddevices.size() > 0) {
    findviewbyid(r.id.title_paired_devices).setvisibility(view.visible);
    for (bluetoothdevice device : paireddevices) {
     mpaireddevicesarrayadapter.add(device.getname() + "\n" + device.getaddress());
    }
   } else {
    string nodevices = getresources().gettext(r.string.none_paired).tostring();
    mpaireddevicesarrayadapter.add(nodevices);
   }
  }
  @override
  protected void ondestroy() {
   super.ondestroy();
   if (mbtadapter != null) {
    mbtadapter.canceldiscovery();
   }
   this.unregisterreceiver(mreceiver);
  }
  private void dodiscovery() {
   findviewbyid(r.id.title_new_devices).setvisibility(view.visible);
   if (mbtadapter.isdiscovering()) {
    mbtadapter.canceldiscovery();
   }
   mbtadapter.startdiscovery(); //开始搜索蓝牙设备并产生广播
    //startdiscovery是一个异步方法
   //找到一个设备时就发送一个bluetoothdevice.action_found的广播
  }
  private onitemclicklistener mpairedeviceclicklistener = new onitemclicklistener() {
   public void onitemclick(adapterview<?> av, view v, int arg2, long arg3) {
    mbtadapter.canceldiscovery();
    string info = ((textview) v).gettext().tostring();
    string address = info.substring(info.length() - 17);
    intent intent = new intent();
    intent.putextra(extra_device_address, address); //mac地址
    setresult(activity.result_ok, intent);
    finish();
   }
  };
  private onitemclicklistener mnewdeviceclicklistener = new onitemclicklistener() {
   public void onitemclick(adapterview<?> av, view v, int arg2, long arg3) {
    mbtadapter.canceldiscovery();
    toast.maketext(devicelist.this, "请在蓝牙设置界面手动连接设备",toast.length_short).show();
    intent intent = new intent(settings.action_bluetooth_settings);
    startactivityforresult(intent,1);
   }
  };
  //回调方法:进入蓝牙配对设置界面返回后执行
  @override
  protected void onactivityresult(int requestcode, int resultcode, intent data) {
   super.onactivityresult(requestcode, resultcode, data);
   init(); //刷新好友列表
  }
 }

蓝牙会话的主activity组件程序fragment.java

public class weixinframent extends fragment {
 public static final int message_state_change = 1;
 public static final int message_read = 2;
 public static final int message_write = 3;
 public static final int message_device_name = 4;
 public static final int message_toast = 5;
 public static final string device_name = "device_name";
 public static final string toast = "toast";
 private static final int request_connect_device = 1; //请求连接设备
 private static final int request_enable_bt = 2;
 private textview mtitle;
 private listview mconversationview;
 private edittext moutedittext;
 private button msendbutton;
 private string mconnecteddevicename = null;
 private arrayadapter<string> mconversationarrayadapter;
 private stringbuffer moutstringbuffer;
 private bluetoothadapter mbluetoothadapter = null;
 private chatservice mchatservice = null;

 private view view;

 public weixinframent() {

 }

 @override
 public view oncreateview(layoutinflater inflater, viewgroup container,
        bundle savedinstancestate) {

  view = inflater.inflate(r.layout.tab_01, container, false);

  toolbar toolbar = view.findviewbyid(r.id.toolbar);
  sethasoptionsmenu(true);

  if (build.version.sdk_int >= build.version_codes.m) {
   if (contextcompat.checkselfpermission(this.getcontext(), manifest.permission.access_coarse_location) != packagemanager.permission_granted) {
    activitycompat.requestpermissions(getactivity(), new string[]{manifest.permission.access_coarse_location}, 1);
   }
  }

  //创建选项菜单
  toolbar.inflatemenu(r.menu.option_menu);
  //选项菜单监听
  toolbar.setonmenuitemclicklistener(new mymenuitemclicklistener());
  mtitle = view.findviewbyid(r.id.title_left_text);
  mtitle.settext(r.string.app_name);
  mtitle = view.findviewbyid(r.id.title_right_text);
  // 得到本地蓝牙适配器
  mbluetoothadapter = bluetoothadapter.getdefaultadapter();
  if (mbluetoothadapter == null) {
   toast.maketext(view.getcontext(), "蓝牙不可用", toast.length_long).show();
   getactivity().finish();
   return view;
  }
  if (!mbluetoothadapter.isenabled()) { //若当前设备蓝牙功能未开启
   intent enableintent = new intent(bluetoothadapter.action_request_enable);
   startactivityforresult(enableintent, request_enable_bt); //
  } else {
   if (mchatservice == null) {
    setupchat(); //创建会话
   }
  }

  return view;
 }

 @override
 public void onrequestpermissionsresult(int requestcode, string[] permissions, int[] grantresults) {
  super.onrequestpermissionsresult(requestcode, permissions, grantresults);
  if (grantresults.length > 0) {
   if (grantresults[0] != packagemanager.permission_granted) {
    toast.maketext(view.getcontext(), "未授权,蓝牙搜索功能将不可用!", toast.length_short).show();
   }
  }
 }

 @override
 public synchronized void onresume() { //synchronized:同步方法实现排队调用
  super.onresume();
  if (mchatservice != null) {
   if (mchatservice.getstate() == chatservice.state_none) {
    mchatservice.start();
   }
  }
 }

 private void setupchat() {
  mconversationarrayadapter = new arrayadapter<string>(view.getcontext(), r.layout.message);
  mconversationview = view.findviewbyid(r.id.in);
  mconversationview.setadapter(mconversationarrayadapter);
  moutedittext = view.findviewbyid(r.id.edit_text_out);
  moutedittext.setoneditoractionlistener(mwritelistener);
  msendbutton = view.findviewbyid(r.id.button_send);
  msendbutton.setonclicklistener(new view.onclicklistener() {
   public void onclick(view v) {
    textview textview = view.findviewbyid(r.id.edit_text_out);
    string message = textview.gettext().tostring();
    sendmessage(message);
   }
  });
  //创建服务对象
  mchatservice = new chatservice(view.getcontext(), mhandler);
  moutstringbuffer = new stringbuffer("");
 }

 @override
 public void ondestroy() {
  super.ondestroy();
  if (mchatservice != null)
   mchatservice.stop();
 }

 private void ensurediscoverable() { //修改本机蓝牙设备的可见性
  //打开手机蓝牙后,能被其它蓝牙设备扫描到的时间不是永久的
  if (mbluetoothadapter.getscanmode() != bluetoothadapter.scan_mode_connectable_discoverable) {
   intent discoverableintent = new intent(bluetoothadapter.action_request_discoverable);
   //设置在300秒内可见(能被扫描)
   discoverableintent.putextra(bluetoothadapter.extra_discoverable_duration, 300);
   startactivity(discoverableintent);
   toast.maketext(view.getcontext(), "已经设置本机蓝牙设备的可见性,对方可搜索了。", toast.length_short).show();
  }
 }

 private void sendmessage(string message) {
  if (mchatservice.getstate() != chatservice.state_connected) {
   toast.maketext(view.getcontext(), r.string.not_connected, toast.length_short).show();
   return;
  }
  if (message.length() > 0) {
   byte[] send = message.getbytes();
   mchatservice.write(send);
   moutstringbuffer.setlength(0);
   moutedittext.settext(moutstringbuffer);
  }
 }

 private textview.oneditoractionlistener mwritelistener = new textview.oneditoractionlistener() {
  @override
  public boolean oneditoraction(textview view, int actionid, keyevent event) {
   if (actionid == editorinfo.ime_null && event.getaction() == keyevent.action_up) {
    //软键盘里的回车也能发送消息
    string message = view.gettext().tostring();
    sendmessage(message);
   }
   return true;
  }
 };
 //使用handler对象在ui主线程与子线程之间传递消息
 private final handler mhandler = new handler() { //消息处理
  @override
  public void handlemessage(message msg) {
   switch (msg.what) {
    case message_state_change:
     switch (msg.arg1) {
      case chatservice.state_connected:
       mtitle.settext(r.string.title_connected_to);
       mtitle.append(mconnecteddevicename);
       mconversationarrayadapter.clear();
       break;
      case chatservice.state_connecting:
       mtitle.settext(r.string.title_connecting);
       break;
      case chatservice.state_listen:
      case chatservice.state_none:
       mtitle.settext(r.string.title_not_connected);
       break;
     }
     break;
    case message_write:
     byte[] writebuf = (byte[]) msg.obj;
     string writemessage = new string(writebuf);
     mconversationarrayadapter.add("我: " + writemessage);
     break;
    case message_read:
     byte[] readbuf = (byte[]) msg.obj;
     string readmessage = new string(readbuf, 0, msg.arg1);
     mconversationarrayadapter.add(mconnecteddevicename + ": "
       + readmessage);
     break;
    case message_device_name:
     mconnecteddevicename = msg.getdata().getstring(device_name);
     toast.maketext(getactivity().getapplicationcontext(), "链接到 " + mconnecteddevicename, toast.length_short).show();
     break;
    case message_toast:
     toast.maketext(getactivity().getapplicationcontext(),
       msg.getdata().getstring(toast), toast.length_short).show();
     break;
   }
  }
 };

 //返回进入好友列表操作后的数回调方法
 public void onactivityresult(int requestcode, int resultcode, intent data) {
  switch (requestcode) {
   case request_connect_device:
    if (resultcode == activity.result_ok) {
     string address = data.getextras().getstring(devicelist.extra_device_address);
     bluetoothdevice device = mbluetoothadapter.getremotedevice(address);
     mchatservice.connect(device);
    } else if (resultcode == activity.result_canceled) {
     toast.maketext(view.getcontext(), "未选择任何好友!", toast.length_short).show();
    }
    break;
   case request_enable_bt:
    if (resultcode == activity.result_ok) {
     setupchat();
    } else {
     toast.maketext(view.getcontext(), r.string.bt_not_enabled_leaving, toast.length_short).show();
     getactivity().finish();
    }
  }
 }

 //内部类,选项菜单的单击事件处理
 private class mymenuitemclicklistener implements toolbar.onmenuitemclicklistener {
  @override
  public boolean onmenuitemclick(menuitem item) {
   switch (item.getitemid()) {
    case r.id.scan:
     //启动devicelist这个activity
     intent serverintent = new intent(weixinframent.this.getactivity(), devicelist.class);
     startactivityforresult(serverintent, request_connect_device);
     return true;
    case r.id.discoverable:
     ensurediscoverable();
     return true;
    case r.id.back:
     getactivity().finish();
     system.exit(0);
     return true;
   }
   return false;
  }
 }
}

项目地址

点我进入仓库

总结

到此这篇关于android在类微信程序中实现蓝牙聊天功能的文章就介绍到这了,更多相关android 类微信程序蓝牙聊天内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!