全网整合营销服务商

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

免费咨询热线: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 


相关文章: 如何快速辨别茅台真假?关键步骤解析  开封网站制作公司,网络用语开封是什么意思?  建站之星24小时客服电话如何获取?  简历在线制作网站免费,免费下载个人简历的网站是哪些?  视频网站app制作软件,有什么好的视频聊天网站或者软件?  C++如何将C风格字符串(char*)转换为std::string?(代码示例)  建站之星代理如何获取技术支持?  大学网站设计制作软件有哪些,如何将网站制作成自己app?  模具网站制作流程,如何找模具客户?  Swift开发中switch语句值绑定模式  SAX解析器是什么,它与DOM在处理大型XML文件时有何不同?  如何在阿里云香港服务器快速搭建网站?  测试制作网站有哪些,测试性取向的权威测试或者网站?  小型网站制作HTML,*游戏网站怎么搭建?  网站按钮制作软件,如何实现网页中按钮的自动点击?  c# 在ASP.NET Core中管理和取消后台任务  如何彻底卸载建站之星软件?  网站建设制作需要多少钱费用,自己做一个网站要多少钱,模板一般多少钱?  存储型VPS适合搭建中小型网站吗?  制作旅游网站html,怎样注册旅游网站?  如何快速搭建个人网站并优化SEO?  如何选择高效响应式自助建站源码系统?    网页设计网站制作软件,microsoft office哪个可以创建网页?  如何在橙子建站中快速调整背景颜色?  网站图片在线制作软件,怎么在图片上做链接?  c# 在高并发下使用反射发射(Reflection.Emit)的性能  如何通过VPS建站无需域名直接访问?  如何通过网站建站时间优化SEO与用户体验?  已有域名如何快速搭建专属网站?  建站之星如何保障用户数据免受黑客入侵?  C#如何序列化对象为XML XmlSerializer用法  香港服务器选型指南:免备案配置与高效建站方案解析  如何使用Golang安装API文档生成工具_快速生成接口文档  官网网站制作腾讯审核要多久,联想路由器newifi官网  制作企业网站建设方案,怎样建设一个公司网站?  如何解决VPS建站LNMP环境配置常见问题?  长沙做网站要多少钱,长沙国安网络怎么样?  在线制作视频的网站有哪些,电脑如何制作视频短片?  如何快速生成凡客建站的专业级图册?  成都品牌网站制作公司,成都营业执照年报网上怎么办理?  如何快速搭建高效WAP手机网站?  免费制作统计图的网站有哪些,如何看待现如今年轻人买房难的情况?  免费制作小说封面的网站有哪些,怎么接网站批量的封面单?  公司门户网站制作公司有哪些,怎样使用wordpress制作一个企业网站?  七夕网站制作视频,七夕大促活动怎么报名?  建站之星北京办公室:智能建站系统与小程序生成方案解析  网站制作话术技巧,网站推广做的好怎么话术?  如何快速搭建安全的FTP站点?  在线ppt制作网站有哪些软件,如何把网页的内容做成ppt? 

您的项目需求

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