4

我的应用程序拥有一个具有特定 的开放式蓝牙服务器套接字UUID,以便另一台设备连接和传输文件。我对BroadcastReceiver.

在我的扩展类中Activity,我想检查蓝牙适配器的状态。但是我的 BroadcastReceiver 永远不会被触发。我尝试以这种方式使用 BroadcastReceiver:

public class MainClass extends Activity {
  public void onCreate(Bundle b) {
  super.onCreate(b);
  IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
  registerReceiver(mReceiver, filter);
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

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

            Log.w("BroadcastReceiver:  ", "Inside!");

            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    Log.d("Bluetooth Receiver", "State-off");
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d("Bluetooth Receiver", "State turning off");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.d("Bluetooth Receiver", "State-on");
                    btCom = new BluetoothCommunicator(MainClass.this, lastCases, nist);
                    btCom.startServer();
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d("Bluetooth Receiver", "State turning on");
                    break;
                }
            }
        }
    };

}

我有一个关于州的问题:

  • 状态STATE_ON是否仅在运行时打开蓝牙时才触发?或者我可以在打开蓝牙的情况下启动我的应用程序,这个事件会被触发吗?btCom.startServer()因为如果打开蓝牙,我想启动该方法

我还读到我需要在我的清单文件中注册广播接收器,如果 BroadcastReceiver 在扩展 Activity 的类中,我该怎么做?如果我在一个单独的类中有这个 BroadcastReceiver 我会这样做

例如说我的包名是com.workbench我的类名是BluetoothReceiver

清单看起来像这样:

 <receiver android:name="com.workbench.BluetoothReceiver"></receiver>
4

1 回答 1

0

BluetoothAdapter.ACTION_STATE_CHANGED当蓝牙适配器的状态改变时发送广播动作。只有当适配器的状态发生变化时,您才会看到这一点。

您可以通过调用来检查蓝牙适配器的当前状态BluetoothAdapter.isEnabled()

BroadcastReceiver如果您想在Intent应用程序未运行时获得广播,您只需在清单中注册。您实现BroadcastReceiver(作为匿名类)的方式不可能在清单中注册它。

于 2013-12-30T18:08:37.053 回答