我有一个问题,我使用 Intent 启动服务,在onCreate()
方法注册BroadcastReceiver
中,然后在onDestroy()
取消注册BroadcastReceiver
. 在方法onHandleIntent()
中,我开始发现蓝牙设备。问题是,我BroadcastReceiver
在找到任何设备之前就被摧毁了,所以我真的无法做任何事情BluetoothDevice.ACTION_FOUND
。我试图移动startDiscovery()
到onCreate()
但没有结果。我的代码如下所示:
public class BluetoothService extends IntentService{
private BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
private final String SMART_TOKEN_ADDRESS = "F0:E7:7E:5F:63:70";
private final BroadcastReceiver receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.v("BLUETOOTH","found it!");
}
};
public BluetoothService() {
super("BluetoothService");
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(){
super.onCreate();
Log.v("SERVICE", "Just got created");
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
btAdapter.startDiscovery();
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.v("BLUETOOTH", "Discovery just started");
//btAdapter.startDiscovery();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v("BLUETOOTH","Just got destroyed!");
unregisterReceiver(receiver);
}
}
日志如下所示: 1. 刚刚创建 2. 发现刚刚开始 3. 刚刚被销毁!4.收到android.bluetooth.device.action.FOUND
感谢帮助!T。