Android studio:如何自动切换开关?

问题描述 投票:0回答:1

如何使开关根据蓝牙的状态自动切换(也必须手动工作)?我需要什么方法?

我有一个简单的开关,可用来手动打开和关闭蓝牙。而且效果很好,但是,如果从另一个应用程序或在手机设置中打开/关闭了蓝牙,则开关当然不会改变。

BluetoothAdapter mBluetAdapter = BluetoothAdapter.getDefaultAdapter();
Switch mySwitch = findViewById(R.id.blueSwc);
mySwitch.setChecked(mBluetAdapter.isEnabled()); //this only works at the beginning
android switch-statement toggle
1个回答
1
投票

您唯一的问题是,您必须聆听蓝牙状态的变化。为此,您需要一个BroadcastReceiever来监听蓝牙适配器的状态。您的其余代码与此都可以。

 private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch(state) {
                case BluetoothAdapter.STATE_OFF:
                    mySwitch.setChecked(false);
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:

                    break;
                case BluetoothAdapter.STATE_ON:
                    mySwitch.setChecked(true);
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:

                    break;
            }

        }
    }
};

像这样注册

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver1, filter1);

    ...
}

并且像这样注销它

@Override
protected void onDestroy() {
    super.onDestroy();

    unregisterReceiver(mBroadcastReceiver1);
}

摘自this answer,其中有如何使用这种类型的BroadcastReceiver的非常详细的描述。

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.