0

我有一个问题,我使用 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。

4

1 回答 1

0

这是因为在处理完所有请求后,服务停止了。来自文档:“在处理完所有启动请求后停止服务,因此您永远不必调用 stopSelf()。”

所以,如果你想使用服务,你应该使用等待或其他命令告诉工作线程等待执行。

请参阅有关服务的文档:http: //developer.android.com/guide/components/services.html

于 2013-10-03T21:23:31.227 回答