蓝牙通信二:测试手机蓝牙当前状态

本文详细介绍了如何在Android平台上测试并获取手机蓝牙的当前状态,包括如何开启、关闭蓝牙,以及检查蓝牙是否可用等关键操作,为进行蓝牙通信开发提供基础支持。

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;

import leon.android.chs_ydw_dcs480_dsp_408.R;

/**
 * Created by Administrator on 2018\9\3 0003.
 */

public class ControlPCActivity extends Activity {
    //    isBlueCon的值   0表示未连接   1表示已经连接   2表示未打开 -1表示未知错误
    //参考网址:https://blog.csdn.net/memoryjs/article/details/42968823
    private BluetoothAdapter ba;           		  //蓝牙适配器
    int isBlueCon;
    TextView tv_contrcol;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contrcol);
        tv_contrcol = (TextView)findViewById(R.id.tv_contrcol);
        ba = BluetoothAdapter.getDefaultAdapter();
        initView();
        tv_contrcol.setText("蓝牙状态为:"+initView());
    }

    private int initView() {
        //蓝牙适配器是否存在,即是否发生了错误
        if (ba == null){
            isBlueCon = -1;     //error
        }else if(ba.isEnabled()){
            int a2dp = ba.getProfileConnectionState(BluetoothProfile.A2DP);				//可操控蓝牙设备,如带播放暂停功能的蓝牙耳机
            int headset = ba.getProfileConnectionState(BluetoothProfile.HEADSET);		//蓝牙头戴式耳机,支持语音输入输出
            int health = ba.getProfileConnectionState(BluetoothProfile.HEALTH);			//蓝牙穿戴式设备
            //查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态
            int flag = -1;
            if (a2dp == BluetoothProfile.STATE_CONNECTED) {
                flag = a2dp;
            } else if (headset == BluetoothProfile.STATE_CONNECTED) {
                flag = headset;
            } else if (health == BluetoothProfile.STATE_CONNECTED) {
                flag = health;
            }
            //说明连接上了三种设备的一种
            if (flag != -1){
                isBlueCon = 1;			//discontinued
            }
        }else {
            isBlueCon = 2;	//shut off
        }
        return  isBlueCon;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值