从非 UI 线程启动服务(蓝牙)
Starting a service from a non-UI thread (Bluetooth)
我在我的应用程序中创建了一个不同的线程,用于创建一个 RFCOMM 套接字来与之通信。但是,我希望实际的通信在服务中完成,这样它就可以在方向改变等愚蠢的事情上持续存在。
像这样:
private class grabSocket extends Thread {
private BluetoothSocket socket = null;
public SocketRetriever(BluetoothDevice device) {
socket = device.createRfcommSocketToServiceRecord(UUID);
}
}
现在如何将此套接字传递给服务?如果我尝试从线程内执行此操作,该服务是否会比线程存活得更久,还是会在线程结束时立即死亡?
如@Submersed 所述,您可以使用活页夹将此套接字传递给您的服务。
If I try to do it from within the thread, will the service outlive the thread, or will it just die as soon as the thread does?
如果您启动一个服务,那么它会一直工作,直到您明确调用 stopService
或 stopSelf
。如果绑定到它,它将一直工作到最后一个客户端解除绑定。因此,服务的生命周期不依赖于线程的生命周期。
我在我的应用程序中创建了一个不同的线程,用于创建一个 RFCOMM 套接字来与之通信。但是,我希望实际的通信在服务中完成,这样它就可以在方向改变等愚蠢的事情上持续存在。
像这样:
private class grabSocket extends Thread {
private BluetoothSocket socket = null;
public SocketRetriever(BluetoothDevice device) {
socket = device.createRfcommSocketToServiceRecord(UUID);
}
}
现在如何将此套接字传递给服务?如果我尝试从线程内执行此操作,该服务是否会比线程存活得更久,还是会在线程结束时立即死亡?
如@Submersed 所述,您可以使用活页夹将此套接字传递给您的服务。
If I try to do it from within the thread, will the service outlive the thread, or will it just die as soon as the thread does?
如果您启动一个服务,那么它会一直工作,直到您明确调用 stopService
或 stopSelf
。如果绑定到它,它将一直工作到最后一个客户端解除绑定。因此,服务的生命周期不依赖于线程的生命周期。