知道是否有任何蓝牙配对设备的行动

时间:2013-09-04 08:34:09

标签: android android-intent filter bluetooth pairing

开始活动时,我需要知道是否有任何蓝牙配对设备,然后根据结果做一些事情。为此,我做下一个:

在onResume:

protected void onResume() {
    super.onResume();

    /**Filters para comprobar el BroadcastReceiver*/
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter1);
    this.registerReceiver(mReceiver, filter2);

然后,我使用BroadcastReceiver:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        /**Do something if connected*/
        if(action.equals("android.bluetooth.device.action.ACL_CONNECTED")) {
            //Action
        }
        /**Do something if disconnected*/
        else if (action.equals("android.bluetooth.device.action.ACL_DISCONNECTED")) {               
            Toast.makeText(getApplicationContext(), "No device paired", Toast.LENGTH_SHORT).show();
        }
    }
};

在清单中:

<activity 
        android:name=".Configuration"
        android:label="@string/config_title" >
        <intent-filter>
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED"/>
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/>
        </intent-filter>
    </activity>

但仍然没有做必须做的事情,所以一定是错的,或者我忘了做某事。

1 个答案:

答案 0 :(得分:1)

如果有人感兴趣,我解决这个问题的方式是:

要检查是否有任何设备连接执行操作,我已经使用了基于BluetoothChat示例应用的方法。

public class Transmission {
    ....

    /**
     * Return the current connection state.
     */
    public synchronized int getState() {
        return GlobalVar.mState;
    }

在本课程中,我只声明了一些变量:

public class GlobalVar {
    ....

    public static int mState;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

最后,这是我执行操作的类,如果有任何连接设备,我想在其中进行初始化检查:

/**Check that we're actually connected before trying anything*/
    if (GlobalVar.mTransmission.getState() == GlobalVar.STATE_CONNECTED) {
        //If there is a conection, do an action
    }
    /**If there is no connection, then shows toast*/
    else {
        Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();