【Android开发 蓝牙连接状态】Android实时检测蓝牙连接状态

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

一、软件界面

【Android开发 蓝牙连接状态】Android实时检测蓝牙连接状态_第1张图片

二、程序实现(源码下载)

①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();
            }
        });

③监听蓝牙连接状态

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
//注册蓝牙监听
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)