在蓝牙扫描结束之前调用Android服务的onDestroy方法

时间:2013-10-03 21:13:41

标签: android service bluetooth broadcastreceiver

我遇到问题,我在onCreate()方法注册BroadcastReceiver中使用Intent启动服务,然后在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.发现才刚刚开始   刚刚被摧毁了!   4.收到android.bluetooth.device.action.FOUND

感谢您的帮助! 吨。

1 个答案:

答案 0 :(得分:0)

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

因此,如果要使用服务,则应使用wait或其他命令告诉工作线程等待执行。

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

相关问题