Android服务被破坏,但不是无限循环

Android服务被破坏,但不是无限循环,android,bluetooth,xamarin,intentservice,Android,Bluetooth,Xamarin,Intentservice,大家好 我的应用程序Xamarin.Android有问题。 我正在尝试编写应扫描蓝牙设备的服务: [Service] internal class BluetoothService : IntentService { ... protected override void OnHandleIntent(Intent intent) { // Thats not working... } public override StartComm

大家好

我的应用程序Xamarin.Android有问题。 我正在尝试编写应扫描蓝牙设备的服务:

[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();
            }
        });
    }
} 
OnStartCommand和ScanledDeviceInLoop服务调用onDestroy后。但我想让这个服务保持活动状态,因为扫描线程是活动的,但服务不活动,并从UI调用StopService停止扫描。但我不能,因为服务已经停止了

有什么建议吗? 谢谢。

IntentService旨在异步执行有限的工作单元

它们处理表示为按需意图的异步请求。 客户端通过StartServiceIntent调用发送请求;这个 服务根据需要启动,使用 工作线程,并在工作线程用完时自动停止

您不应该为您的应用程序重写OnStartCommand方法 意向服务。相反,重写OnHandleIntentIntent,它 当IntentService收到启动请求时,系统调用

在您的情况下,服务可能会停止,因为他完成了OnHandleContent中的所有工作,而这一点都没有


我建议您使用服务类,但请记住,您应该手动创建新线程,因为服务与在主线程上工作的IntentService不同

如果将在另一个线程中使用服务而不是IntentService,那么该服务在应用程序后是否会停止工作?是的,如果您使用StartForeground方法启动服务