監聽手機藍牙的廣播——打開和關閉藍牙

廣播類如下:

 //藍牙廣播
    public class BlueToothStateReceiver extends BroadcastReceiver {
        public int DEFAULT_VALUE_BULUETOOTH = 1000;
        //public OnBlueToothStateListener onBlueToothStateListener;

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, DEFAULT_VALUE_BULUETOOTH);
                switch (state) {
                    case BluetoothAdapter.STATE_OFF://藍牙已關閉
                        //onBlueToothStateListener.onStateOff();
                        open.setChecked(false);
                        break;
                    case BluetoothAdapter.STATE_ON://藍牙已開啓
                        //onBlueToothStateListener.onStateOn();
                        open.setChecked(true);
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON://藍牙正在打開
                      //  onBlueToothStateListener.onStateTurningOn();
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF://藍牙正在關閉
                        //onBlueToothStateListener.onStateTurningOff();
                        break;
                    default:
                        Log.e("BlueToothError", "藍牙狀態未知");
                }
            }
        }
    }
主界面調用

 //藍牙廣播
         intentFilter = new IntentFilter();
         blueToothStateReceiver=new BlueToothStateReceiver();
         intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//藍牙廣播
         registerReceiver(blueToothStateReceiver,intentFilter);

打開和關閉藍牙

//這裏的open是Switch,一個開關打開關閉藍牙
 open.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                                            @Override
                                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                                if (isChecked){
                                                    Toast.makeText(MainActivity.this,"打開藍牙",Toast.LENGTH_LONG).show();
                                                    mBluetoothAdapter.enable();//打開藍牙
                                                }else {
                                                    mBluetoothAdapter.disable();//打開藍牙
                                                    Toast.makeText(MainActivity.this,"關閉藍牙",Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        }
                );
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章