广播接收器使用蓝牙连接状态动态更改CheckBox状态

时间:2016-06-20 06:35:59

标签: android checkbox bluetooth broadcastreceiver

我的活动中有一个复选框。我希望在蓝牙打开时选中此复选框,并在关闭时取消选中。我知道定期检查蓝牙状态是一种低效的方式。所以我需要使用BroadcastReciever。我尝试在我的活动中使用以下代码执行此操作。但它不起作用。我不确定我是否正确使用了BroadcastReciever。[new to this] 这是我的代码。

 package com.example.sample;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.Toast;

public class BluetoothActivity extends AppCompatActivity {

    public CheckBox btcheck;
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive (Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
                        == BluetoothAdapter.STATE_OFF){
                    btcheck.setChecked(false);
                }
                else{
                    btcheck.setChecked(true);
                }
            }

        }

    };

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

        btcheck=(CheckBox)findViewById(R.id.btcheck);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(mReceiver,filter);



    }
}

0 个答案:

没有答案