android蓝牙开启和关闭

一、允许蓝牙权限

 AndroidManifest.xml中加入


 //此句不加,在onDestroy()函数中用mBluetoothAdapter.disable();会报错

二-1、检测并启动蓝牙功能

 1、全局静态常量中定义

 public static final int REQUEST_ENABLE_BT = 1;

 //如果采取直接启动,这句可不要

 2、全局变量中定义

 // 得到BluetoothAdapter

 BluetoothAdapter mBluetoothAdapter;

 3、public void InitParameter(){ }中加入

 //初始化 BluetoothAdapter

 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

 4-1、直接启动蓝牙方式

 在需要启动的地方加入

 mBluetoothAdapter.enable();

 4-2、弹出对话框方式启动蓝牙

 建立初始化蓝牙函数InitBluetooth()

public void InitBluetooth(BluetoothAdapter mBluetoothAdapter) {

if (mBluetoothAdapter == null) {

// Device does not support Bluetooth

}

// 启用蓝牙 ( 2.Enable Bluetooth )

if (!mBluetoothAdapter.isEnabled()) {

Intent enableBtIntent = new Intent(

BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

}

三、在退出(onDestroy())时关闭蓝牙

在@Override

protected void onDestroy() 中加入

 mBluetoothAdapter.disable();

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.简介 通过蓝牙API,可以实现以下内容: 扫描其他蓝牙设备 查询配对蓝牙设备的本地蓝牙适配器 创建RFCOMM...
    justCode_阅读 5,062评论 0 3
  • 前言 此外本文只涉及经典蓝牙(Classic Bluetooth)的点对点通信开发,并不涉及低功耗蓝牙(BLE)的...
    杨卢阳阅读 4,319评论 5 15
  • Key Terms And Concepts 关键术语和概念 Here is a summary of key B...
    Jaesoon阅读 2,463评论 0 5
  • 海伦·凯勒曾说:坚定的信心,能使平凡的人们,做出惊人的事业。对凌驾命运之上的人来说,信心就是生命的主宰。”作家路遥...
    很多人都叫张宁阅读 662评论 0 0
  • 香火 我们那过年天气一点也不冷。 日日都是晴空高照,难见雨雪。阳光垂在人身上,晒得人发酥发软。从外乡带回来的羽绒衣...
    陈同往阅读 323评论 0 0