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

Android 扫描附近的蓝牙设备并连接蓝牙音响的示例

程序员文章站 2023-12-19 15:42:16
写了一个可以扫描附近蓝牙设备的小demo,可以查看蓝牙设备的设备名和mac地址 代码量不多,很容易看懂 /** * 作者:叶应是叶 * 时间:201...

写了一个可以扫描附近蓝牙设备的小demo,可以查看蓝牙设备的设备名和mac地址

代码量不多,很容易看懂

/**
 * 作者:叶应是叶
 * 时间:2017/9/8 20:13
 * 描述:
 */
public class scandeviceactivity extends appcompatactivity {

 private loadingdialog loadingdialog;

 private deviceadapter deviceadapter;

 private bluetoothadapter bluetoothadapter;

 private handler handler = new handler();

 private broadcastreceiver discoveryreceiver = new broadcastreceiver() {
  @override
  public void onreceive(context context, intent intent) {
   switch (intent.getaction()) {
    case bluetoothadapter.action_discovery_started:
     showloadingdialog("正在搜索附近的蓝牙设备");
     break;
    case bluetoothadapter.action_discovery_finished:
     toast.maketext(scandeviceactivity.this, "搜索结束", toast.length_short).show();
     hideloadingdialog();
     break;
    case bluetoothdevice.action_found:
     bluetoothdevice bluetoothdevice = intent.getparcelableextra(bluetoothdevice.extra_device);
     deviceadapter.adddevice(bluetoothdevice);
     deviceadapter.notifydatasetchanged();
     break;
   }
  }
 };


 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_scan_device);
  bluetoothmanager bluetoothmanager = (bluetoothmanager) getsystemservice(context.bluetooth_service);
  bluetoothadapter = bluetoothmanager.getadapter();
  if (bluetoothadapter == null) {
   toast.maketext(this, "当前设备不支持蓝牙", toast.length_short).show();
   finish();
  }
  initview();
  registerdiscoveryreceiver();
  startscan();
 }

 @override
 protected void ondestroy() {
  super.ondestroy();
  handler.removecallbacksandmessages(null);
  unregisterreceiver(discoveryreceiver);
  if (bluetoothadapter.isdiscovering()) {
   bluetoothadapter.canceldiscovery();
  }
 }

 private void initview() {
  listview lv_devicelist = (listview) findviewbyid(r.id.lv_devicelist);
  deviceadapter = new deviceadapter(this);
  lv_devicelist.setadapter(deviceadapter);
 }

 private void registerdiscoveryreceiver() {
  intentfilter intentfilter = new intentfilter();
  intentfilter.addaction(bluetoothadapter.action_discovery_started);
  intentfilter.addaction(bluetoothadapter.action_discovery_finished);
  intentfilter.addaction(bluetoothdevice.action_found);
  intentfilter.addaction(bluetoothdevice.action_bond_state_changed);
  registerreceiver(discoveryreceiver, intentfilter);
 }

 private void startscan() {
  if (!bluetoothadapter.isenabled()) {
   if (bluetoothadapter.enable()) {
    handler.postdelayed(new runnable() {
     @override
     public void run() {
      scandevice();
     }
    }, 1500);
   } else {
    toast.maketext(this, "请求蓝牙权限被拒绝,请授权", toast.length_short).show();
   }
  } else {
   scandevice();
  }
 }

 private void scandevice() {
  if (bluetoothadapter.isdiscovering()) {
   bluetoothadapter.canceldiscovery();
  }
  bluetoothadapter.startdiscovery();
 }

 private void showloadingdialog(string message) {
  if (loadingdialog == null) {
   loadingdialog = new loadingdialog(this);
  }
  loadingdialog.show(message, true, false);
 }

 private void hideloadingdialog() {
  if (loadingdialog != null) {
   loadingdialog.dismiss();
  }
 }

}

此外,还可以通过利用反射来调用系统api,从而与支持蓝牙a2dp协议的蓝牙音响连接上,不过因为我只有一部不算严格意义上的蓝牙音响来做测试,所以这个功能并不确定是否适用于大多数蓝牙设备

/**
 * 作者:叶应是叶
 * 时间:2017/9/8 20:02
 * 描述:
 */
public class connecta2dpactivity extends appcompatactivity {

 private deviceadapter deviceadapter;

 private bluetoothadapter bluetoothadapter;

 private handler handler = new handler();

 private bluetootha2dp bluetootha2dp;

 private loadingdialog loadingdialog;

 private final string tag = "connecta2dpactivity";

 private broadcastreceiver a2dpreceiver = new broadcastreceiver() {

  @override
  public void onreceive(context context, intent intent) {
   switch (intent.getaction()) {
    case bluetootha2dp.action_connection_state_changed:
     int connectstate = intent.getintextra(bluetootha2dp.extra_state, bluetootha2dp.state_disconnected);
     if (connectstate == bluetootha2dp.state_disconnected) {
      toast.maketext(connecta2dpactivity.this, "已断开连接", toast.length_short).show();
     } else if (connectstate == bluetootha2dp.state_connected) {
      toast.maketext(connecta2dpactivity.this, "已连接", toast.length_short).show();
     }
     break;
    case bluetootha2dp.action_playing_state_changed:
     int playstate = intent.getintextra(bluetootha2dp.extra_state, bluetootha2dp.state_not_playing);
     if (playstate == bluetootha2dp.state_playing) {
      toast.maketext(connecta2dpactivity.this, "处于播放状态", toast.length_short).show();
     } else if (playstate == bluetootha2dp.state_not_playing) {
      toast.maketext(connecta2dpactivity.this, "未在播放", toast.length_short).show();
     }
     break;
   }
  }
 };

 private broadcastreceiver discoveryreceiver = new broadcastreceiver() {
  @override
  public void onreceive(context context, intent intent) {
   switch (intent.getaction()) {
    case bluetoothadapter.action_discovery_started:
     showloadingdialog("正在搜索蓝牙设备,搜索时间大约一分钟");
     break;
    case bluetoothadapter.action_discovery_finished:
     toast.maketext(connecta2dpactivity.this, "搜索蓝牙设备结束", toast.length_short).show();
     hideloadingdialog();
     break;
    case bluetoothdevice.action_found:
     bluetoothdevice bluetoothdevice = intent.getparcelableextra(bluetoothdevice.extra_device);
     deviceadapter.adddevice(bluetoothdevice);
     deviceadapter.notifydatasetchanged();
     break;
    case bluetoothdevice.action_bond_state_changed:
     int status = intent.getintextra(bluetoothdevice.extra_bond_state, bluetoothdevice.bond_none);
     if (status == bluetoothdevice.bond_bonded) {
      toast.maketext(connecta2dpactivity.this, "已连接", toast.length_short).show();
     } else if (status == bluetoothdevice.bond_none) {
      toast.maketext(connecta2dpactivity.this, "未连接", toast.length_short).show();
     }
     hideloadingdialog();
     break;
   }
  }
 };

 private bluetoothprofile.servicelistener profileservicelistener = new bluetoothprofile.servicelistener() {

  @override
  public void onservicedisconnected(int profile) {
   if (profile == bluetoothprofile.a2dp) {
    toast.maketext(connecta2dpactivity.this, "onservicedisconnected", toast.length_short).show();
    bluetootha2dp = null;
   }
  }

  @override
  public void onserviceconnected(int profile, final bluetoothprofile proxy) {
   if (profile == bluetoothprofile.a2dp) {
    toast.maketext(connecta2dpactivity.this, "onserviceconnected", toast.length_short).show();
    bluetootha2dp = (bluetootha2dp) proxy;
   }
  }
 };

 private adapterview.onitemclicklistener itemclicklistener = new adapterview.onitemclicklistener() {
  @override
  public void onitemclick(adapterview<?> parent, view view, int position, long id) {
   bluetoothdevice device = deviceadapter.getdevice(position);
   if (device.getbondstate() == bluetoothdevice.bond_bonded) {
    toast.maketext(connecta2dpactivity.this, "已连接该设备", toast.length_short).show();
    return;
   }
   showloadingdialog("正在连接");
   connecta2dp(device);
  }
 };


 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_connect_a2dp);
  bluetoothmanager bluetoothmanager = (bluetoothmanager) getsystemservice(context.bluetooth_service);
  bluetoothadapter = bluetoothmanager.getadapter();
  if (bluetoothadapter == null || !getpackagemanager().hassystemfeature(packagemanager.feature_bluetooth_le)) {
   toast.maketext(connecta2dpactivity.this, "当前设备不支持蓝牙", toast.length_short).show();
   finish();
  }
  bluetoothadapter.getprofileproxy(this, profileservicelistener, bluetoothprofile.a2dp);
  initview();
  registerdiscoveryreceiver();
  registera2dpreceiver();
  startscan();
 }

 @override
 protected void ondestroy() {
  super.ondestroy();
  handler.removecallbacksandmessages(null);
  unregisterreceiver(a2dpreceiver);
  unregisterreceiver(discoveryreceiver);
  if (bluetoothadapter.isdiscovering()) {
   bluetoothadapter.canceldiscovery();
  }
 }

 private void initview() {
  listview lv_devicelist = (listview) findviewbyid(r.id.lv_devicelist);
  deviceadapter = new deviceadapter(this);
  lv_devicelist.setadapter(deviceadapter);
  lv_devicelist.setonitemclicklistener(itemclicklistener);
 }

 private void registerdiscoveryreceiver() {
  intentfilter intentfilter = new intentfilter();
  intentfilter.addaction(bluetoothadapter.action_discovery_started);
  intentfilter.addaction(bluetoothadapter.action_discovery_finished);
  intentfilter.addaction(bluetoothdevice.action_found);
  intentfilter.addaction(bluetoothdevice.action_bond_state_changed);
  registerreceiver(discoveryreceiver, intentfilter);
 }

 private void registera2dpreceiver() {
  intentfilter intentfilter = new intentfilter();
  intentfilter.addaction(bluetootha2dp.action_connection_state_changed);
  intentfilter.addaction(bluetootha2dp.action_playing_state_changed);
  registerreceiver(a2dpreceiver, intentfilter);
 }

 private void startscan() {
  if (!bluetoothadapter.isenabled()) {
   if (bluetoothadapter.enable()) {
    handler.postdelayed(new runnable() {
     @override
     public void run() {
      scandevice();
     }
    }, 1500);
   } else {
    toast.maketext(connecta2dpactivity.this, "请求蓝牙权限被拒绝", toast.length_short).show();
   }
  } else {
   scandevice();
  }
 }

 private void scandevice() {
  if (bluetoothadapter.isdiscovering()) {
   bluetoothadapter.canceldiscovery();
  }
  bluetoothadapter.startdiscovery();
 }

 public void setpriority(bluetoothdevice device, int priority) {
  try {
   method connectmethod = bluetootha2dp.class.getmethod("setpriority", bluetoothdevice.class, int.class);
   connectmethod.invoke(bluetootha2dp, device, priority);
  } catch (exception e) {
   e.printstacktrace();
  }
 }

 private void connecta2dp(bluetoothdevice bluetoothdevice) {
  if (bluetootha2dp == null || bluetoothdevice == null) {
   return;
  }
  setpriority(bluetoothdevice, 100);
  try {
   method connectmethod = bluetootha2dp.class.getmethod("connect", bluetoothdevice.class);
   connectmethod.invoke(bluetootha2dp, bluetoothdevice);
  } catch (exception e) {
   e.printstacktrace();
  }
 }

 private void showloadingdialog(string message) {
  if (loadingdialog == null) {
   loadingdialog = new loadingdialog(this);
  }
  loadingdialog.show(message, true, false);
 }

 private void hideloadingdialog() {
  if (loadingdialog != null) {
   loadingdialog.dismiss();
  }
 }

}

这里给出源代码供大家参考:bluetoothdemo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: