0

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

在 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);

然后,我使用广播接收器:

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>

但是仍然没有做它认为必须做的事情,所以一定是出了什么问题,或者我忘了做某事。

4

1 回答 1

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();
于 2013-09-04T10:27:51.127 回答