[英]Android service destroyed, but not infinite loop
Everybody! 大家!
I have a problem with my app (Xamarin.Android). 我的应用程序(Xamarin.Android)出现问题。 I'm trying to write service which should scan Bluetooth devices:
我正在尝试编写应扫描蓝牙设备的服务:
[Service]
internal class BluetoothService : IntentService
{
...
protected override void OnHandleIntent(Intent intent)
{
// Thats not working...
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
_bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
ScanLeDeviceInLoop(true);
return StartCommandResult.Sticky;
}
private async void ScanLeDeviceInLoop(bool enable)
{
await Task.Factory.StartNew(async () =>
{
if (enable == _loopScanningEnabled)
return;
_loopScanningEnabled = enable;
while (_loopScanningEnabled)
{
_container.Clear();
_bluetoothAdapter.StartLeScan(_leScanCallback);
await Task.Factory.StartNew(() => System.Threading.Thread.Sleep((int)_scanPeriod.TotalMilliseconds));
_bluetoothAdapter.StopLeScan(_leScanCallback);
OnScanCompleted();
}
});
}
}
After OnStartCommand and ScanLeDeviceInLoop service call onDestroy. 在OnStartCommand和ScanLeDeviceInLoop服务之后,调用onDestroy。 But I want to keep this service alive (thread with scanning is alive, but service not) and call StopService from UI to stop scanning.
但是我想保持此服务的活动状态(具有扫描功能的线程处于活动状态,但服务未处于活动状态),并从UI调用StopService以停止扫描。 But I can't due to service is already stopped.
但是由于服务我已经不能停止了。
Any suggestion? 有什么建议吗? Thanks.
谢谢。
IntentService
are designed to perform finite units of work asynchronously. IntentService
设计为异步执行有限的工作单元。
They handle asynchronous requests (expressed as
Intents
) on demand.它们按需处理异步请求(表示为
Intents
)。 Clients send requests throughStartService(Intent)
calls;客户端通过
StartService(Intent)
调用发送请求; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.该服务将根据需要启动,使用工作线程依次处理每个Intent,并在工作耗尽时自行停止。
You should not override
OnStartCommand
method for yourIntentService
.您不应为
IntentService
重写OnStartCommand
方法。 Instead, overrideOnHandleIntent(Intent)
, which the system calls when theIntentService
receives a start request.而是重写
OnHandleIntent(Intent)
,当IntentService
收到启动请求时,系统将调用该IntentService
。
In your situation service probably stops because he finished all the work in OnHandleIntent
which is none. 在您的情况下,服务可能会停止,因为他在
OnHandleIntent
完成了所有工作,但没有完成。
I recommend you to use Service
class, but remember that you should create your new thread manually, because Service
unlike IntentService
working on the main thread 我建议您使用
Service
类,但是请记住您应该手动创建新线程,因为Service
与IntentService
不同,它在主线程上工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.