全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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

写了一个可以扫描附近蓝牙设备的小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

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


# android  # 扫描蓝牙设备  # 连接蓝牙设备  # Android蓝牙通信之搜索蓝牙设备  # Android获取蓝牙设备列表的方法  # 不支持  # 应是  # 被拒  # 还可以  # 我只  # 不多  # 适用于  # 很容易  # 写了  # 来做  # 源代码  # 大家多多  # 可以查看  # 看懂  # 而与  # 射来  # 支持蓝牙  # 意义上  # notifyDataSetChanged  # protected 


相关文章: 广德云建站网站建设方案与建站流程优化指南  建站之星如何快速解决建站难题?  历史网站制作软件,华为如何找回被删除的网站?  建站之星免费模板:自助建站系统与智能响应式一键生成  电商平台网站制作流程,电商网站如何制作?  购物网站制作公司有哪些,哪个购物网站比较好?  极客网站有哪些,DoNews、36氪、爱范儿、虎嗅、雷锋网、极客公园这些互联网媒体网站有什么差异?  建站主机解析:虚拟主机配置与服务器选择指南  网站专业制作公司,网站编辑是做什么的?好做吗?工作前景如何?  html制作网站的步骤有哪些,iapp如何添加网页?  建站之星各版本价格是多少?  建站之星伪静态规则如何正确配置?  如何快速搭建支持数据库操作的智能建站平台?  ,购物网站怎么盈利呢?  如何快速搭建虚拟主机网站?新手必看指南  如何通过虚拟机搭建网站?详细步骤解析  香港网站服务器数量如何影响SEO优化效果?  湖南网站制作公司,湖南上善若水科技有限公司做什么的?  建站主机是什么?如何选择适合的建站主机?  如何配置FTP站点权限与安全设置?  图册素材网站设计制作软件,图册的导出方式有几种?  建站之星手机一键生成:多端自适应+小程序开发快速建站指南  ,网页ppt怎么弄成自己的ppt?  陕西网站制作公司有哪些,陕西凌云电器有限公司官网?  香港服务器网站测试全流程:性能评估、SEO加载与移动适配优化  如何快速登录WAP自助建站平台?  网站制作与设计教程,如何制作一个企业网站,建设网站的基本步骤有哪些?  C++如何使用std::optional?(处理可选值)  如何在Ubuntu系统下快速搭建WordPress个人网站?  微网站制作教程,不会写代码,不会编程,怎么样建自己的网站?  官网建站费用明细查询_企业建站套餐价格及收费标准指南  图片制作网站免费软件,有没有免费的网站或软件可以将图片批量转为A4大小的pdf?  如何在阿里云完成域名注册与建站?  建站主机系统SEO优化与智能配置核心关键词操作指南  GML (Geography Markup Language)是什么,它如何用XML来表示地理空间信息?  实惠建站价格推荐:2025年高性价比自助建站套餐解析  如何选择高效便捷的WAP商城建站系统?  网站制作公司排行榜,抖音怎样做个人官方网站  如何制作公司的网站链接,公司想做一个网站,一般需要花多少钱?  如何在Golang中使用replace替换模块_指定本地或远程路径  PHP 500报错的快速解决方法  浙江网站制作公司有哪些,浙江栢塑信息技术有限公司定制网站做的怎么样?  如何用PHP快速搭建高效网站?分步指南  如何在IIS管理器中快速创建并配置网站?  如何通过PHP快速构建高效问答网站功能?  b2c电商网站制作流程,b2c水平综合的电商平台?  建站之星IIS配置教程:代码生成技巧与站点搭建指南  代刷网站制作软件,别人代刷火车票靠谱吗?  宝塔建站助手安装配置与建站模板使用全流程解析  如何在企业微信快速生成手机电脑官网? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。