简体   繁体   中英

Android service destroyed, but not infinite loop

Everybody!

I have a problem with my app (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. But I want to keep this service alive (thread with scanning is alive, but service not) and call StopService from UI to stop scanning. But I can't due to service is already stopped.

Any suggestion? Thanks.

IntentService are designed to perform finite units of work asynchronously.

They handle asynchronous requests (expressed as Intents ) on demand. Clients send requests through StartService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

You should not override OnStartCommand method for your IntentService . Instead, override OnHandleIntent(Intent) , which the system calls when the IntentService receives a start request.

In your situation service probably stops because he finished all the work in OnHandleIntent which is none.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM