蓝牙通信二:测试手机蓝牙当前状态
发布日期:2021-05-09 18:26:52 浏览次数:19 分类:原创文章

本文共 1989 字,大约阅读时间需要 6 分钟。

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;    }}

 

上一篇:java求数组最大值、最小值和下标位置、数组相邻值
下一篇:蓝牙一:蓝牙的简单使用,包括打开蓝牙和关闭蓝牙

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月20日 18时04分43秒