首页 > 系统 > Android > 正文

Android开发实现实时检测蓝牙连接状态的方法【附源码下载】

2019-10-22 18:22:17
字体:
来源:转载
供稿:网友

本文实例讲述了Android开发实现实时检测蓝牙连接状态的方法。分享给大家供大家参考,具体如下:

本程序能实时监听并检测Android蓝牙的连接状态,无论是通过界面上的switch按钮打开/关闭手机蓝牙,还是手动打开/关闭手机蓝牙,程序都能监听当前的状态。

一、软件界面

Android,实时检测,蓝牙,连接状态,源码下载

二、程序实现

① switch开关—-打开/关闭蓝牙

Switch switchTest = (Switch) findViewById(R.id.switch1);switchTest.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  if (isChecked) {   mBluetoothAdapter.enable();//打开蓝牙  } else {   mBluetoothAdapter.disable();// 关闭蓝牙  } }});

② 查看蓝牙状态监听

Button btn = (Button) findViewById(R.id.button);btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {  Toast.makeText(MainActivity.this, "bluetooth is " +bluetoothStatus,    Toast.LENGTH_SHORT).show(); }});

③ 监听蓝牙连接状态

AndroidManifest权限设置:

<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

可点击此处查看Android权限设置

监听代码:

//注册蓝牙监听mContext.registerReceiver(mReceiver, makeFilter());//注销蓝牙监听//mContext.unregisterReceiver(mReceiver);private IntentFilter makeFilter() {  IntentFilter filter = new IntentFilter();  filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  return filter;}private BroadcastReceiver mReceiver = new BroadcastReceiver() {  @Override  public void onReceive(Context context, Intent intent) {   switch (intent.getAction()) {    case BluetoothAdapter.ACTION_STATE_CHANGED:     int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);     switch (blueState) {      case BluetoothAdapter.STATE_TURNING_ON:       Log.e("TAG", "TURNING_ON");       break;      case BluetoothAdapter.STATE_ON:       bluetoothStatus="on";       Log.e("TAG", "STATE_ON");       break;      case BluetoothAdapter.STATE_TURNING_OFF:       Log.e("TAG", "STATE_TURNING_OFF");       break;      case BluetoothAdapter.STATE_OFF:       bluetoothStatus="off";       Log.e("TAG", "STATE_OFF");       break;     }     break;   }  }};

:完整实例代码点击此处本站下载

希望本文所述对大家Android程序设计有所帮助。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表