最近写项目,需要用到蓝牙功能,为了方便自己和他人今后使用。鄙人便顺手将其封装成了工具类。
在此之前,我们需要先在清单文件添加下蓝牙权限:
AndroidManifest.xml中添加权限代码
<!-- 添加蓝牙权限-->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
任意一个Actvity界面,打开蓝牙。
打开蓝牙
1.在需要开启蓝牙的地方添加如下代码:
myOpenBlueTooth();//打开蓝牙
2 . 复制封装方法代码到当前活动界面中
private void myOpenBlueTooth() {
// TODO Auto-generated method stub
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
if (ba != null) {//如果有蓝牙设备
if (!ba.isEnabled())//如果蓝牙没有打开
{
/************************
* 打开蓝牙方法
*
* 方法一:有提示信息地打开蓝牙
*
*************************/
Intent intent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
/***********************
* 方法二:无提示开启蓝牙
* *********************/
//ba.enable();//静默开启蓝牙
}
} else {
Toast.makeText(this, "对不起,您的设备不支持蓝牙",Toast.LENGTH_SHORT).show();
}
}
关闭蓝牙
1.在需要关闭蓝牙的地方添加如下代码
myCloseBlueTooth();
2.复制封装方法代码到当前活动界面中
private void myCloseBlueTooth() {
// TODO Auto-generated method stub
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
if (ba != null) {//如果有蓝牙设备
if (ba.isEnabled())//如果蓝牙打开
{
ba.disable();//关闭蓝牙
}
} else {
Toast.makeText(this, "对不起,您的设备不支持蓝牙",Toast.LENGTH_SHORT).show();
}
}
调用Demo
MainActivity.java
package com.xingyun.studybluetoothactivity;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
//活动被创建时打开蓝牙
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOpenBlueTooth();//打开蓝牙
}
//活动被销毁时关闭蓝牙
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
myCloseBlueTooth();//关闭蓝牙
}
//打开蓝牙方法
private void myOpenBlueTooth() {
// TODO Auto-generated method stub
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
if (ba != null) {// 如果有蓝牙设备
if (!ba.isEnabled())// 如果蓝牙没有打开
{
/************************
* 打开蓝牙方法
*
* 方法一:有提示信息地打开蓝牙
*
*************************/
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
/***********************
* 方法二:无提示开启蓝牙
* *********************/
// ba.enable();//静默开启蓝牙
}
} else {
Toast.makeText(this, "对不起,您的设备不支持蓝牙", Toast.LENGTH_SHORT).show();
}
}
//关闭蓝牙方法
private void myCloseBlueTooth() {
// TODO Auto-generated method stub
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
if (ba != null) {//如果有蓝牙设备
if (ba.isEnabled())//如果蓝牙打开
{
ba.disable();//关闭蓝牙
}
} else {
Toast.makeText(this, "对不起,您的设备不支持蓝牙",Toast.LENGTH_SHORT).show();
}
}
}
本文标题:Android打开/关闭蓝牙封装工具类
本文链接:https://blog.quwenai.cn/post/3002.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。






还没有评论,来说两句吧...