我正在开发一个Android应用程序,它使用蓝牙连接到远程设备(特别是HC-05蓝牙模块)。目前,我正在努力在BroadcastReceiver
课程中正确注册一些Service
。
我想要实现的目标是:
MainActivity
Button
onClickListener
ConnectionService
,会启动onStartCommand
。onReceive
方法中,我注册先前创建的接收者(作为服务类中的字段)。BluetoothDevice.ACTION_FOUND
方法中,该方法设置为侦听connectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(Constants.TAG,"CONNECT button clicked. Starting ConnectionService");
Intent startConnectionServiceIntent = new Intent(MainActivity.this, ConnectionService.class);
Context context = getApplicationContext();
context.startService(startConnectionServiceIntent);
。
[我知道,这不是一件非常复杂的事情......] BUT: 当我注册接收器并开始发现时,似乎接收器不工作。我的意思是,他们没有接受行动。
我的代码如下所示:
在MainActivity中:
public class ConnectionService extends Service {
private BluetoothAdapter BA;
private ConnectionStarterThread connectionStarter;
private ConnectThread connectThread;
private ConnectedThread connectedThread;
private BluetoothSocket socket;
private boolean deviceFound;
private final BroadcastReceiver actionFoundReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
[...]
deviceFound = true;
BA.cancelDiscovery();
[...]
}
else {
deviceFound = false;
}
}
}
};
private final BroadcastReceiver discoveryStartedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
// do something
}
}
};
private final BroadcastReceiver discoveryFinishedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// do something else
}
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
BA = BluetoothAdapter.getDefaultAdapter();
registerReceiver(actionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(discoveryStartedReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(discoveryFinishedReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
Log.d(Constants.TAG, "ConnectionService started");
BA.startDiscovery();
connectionStarter = new ConnectionStarterThread();
connectionStarter.run();
return super.onStartCommand(intent, flags, startId);
}
在ConnectionService中:
connectionStarter = new ConnectionStarterThread();
connectionStarter.run();
问题是:我做错了什么?
指定 - 此代码:
Thread
负责创建deviceFound
,可以重复检查true
变量是否已设置为actionFoundReceiver
(应由BroadcastReceivers
处理),如果是,则启动蓝牙连接(这是根据Android Developers示例中的建议完成的)。也许问题出在这里?
我已尝试过的内容:
BroadcastReceiver
作为{{1}}类的子类 - 没有帮助。有人可以帮我解决这个问题吗?有简单的方法吗?