在Android Studio中更新交换机上的蓝牙状态

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

我从在Android Studio上的Android Apps编程开始,然后在一个简单的蓝牙打开/关闭开关上进行练习,该开关可以正常工作,可以激活和停用蓝牙,但是如果我通过状态栏上的快速设置激活或停用了蓝牙(无关闭应用程序)开关不会更新。我认为该应用失去了焦点,因此我尝试验证蓝牙状态并更新onResume上的开关,但它不起作用。有什么想法吗?

public class bluetooth_Control extends AppCompatActivity{

    Switch aSwitch;
    BluetoothAdapter blueadp;

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

        aSwitch = (Switch) findViewById(R.id.switch2);
        blueadp =   BluetoothAdapter.getDefaultAdapter();



        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){

                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, 0);

                }
                else{

                    blueadp.disable();
                }
            }
        });

    }



    @Override
    protected void onResume(){
        super.onResume();
        setBTswitch(blueadp);
    }


    public void setBTswitch(BluetoothAdapter b){
        if(b.isEnabled()){
            aSwitch.setChecked(true);
        }
        else{
            aSwitch.setChecked(false);
        }
    }
}

android android-studio-3.0
1个回答
0
投票

您应该添加有关“更新onResume()上的开关”的代码,否则我们将无法找出问题所在。我建议在onResume()回调中添加日志,以检查获取蓝牙状态的代码是否工作正常。

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