[英]Android service destroyed, but not infinite loop
大家!
我的應用程序(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和ScanLeDeviceInLoop服務之后,調用onDestroy。 但是我想保持此服務的活動狀態(具有掃描功能的線程處於活動狀態,但服務未處於活動狀態),並從UI調用StopService以停止掃描。 但是由於服務我已經不能停止了。
有什么建議嗎? 謝謝。
IntentService
設計為異步執行有限的工作單元。
它們按需處理異步請求(表示為
Intents
)。 客戶端通過StartService(Intent)
調用發送請求; 該服務將根據需要啟動,使用工作線程依次處理每個Intent,並在工作耗盡時自行停止。您不應為
IntentService
重寫OnStartCommand
方法。 而是重寫OnHandleIntent(Intent)
,當IntentService
收到啟動請求時,系統將調用該IntentService
。
在您的情況下,服務可能會停止,因為他在OnHandleIntent
完成了所有工作,但沒有完成。
我建議您使用Service
類,但是請記住您應該手動創建新線程,因為Service
與IntentService
不同,它在主線程上工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.