我的应用程序拥有一个具有特定 的开放式蓝牙服务器套接字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>