我的应用程序在后台运行时具有以下流程:
OneTimeWorkRequest
启动JobIntentService
,依次进入onHandleWork()
方法调用runService()
(我的方法)。
private void runService(final Context ctx, final IndoorOutdoorManager.AggregatedDetectionListener detectionListener, long mode, long requestedTimeout, final int trigger) {
this.acquireWakeLock();
// Get the requested manager's timeout.
long managerTimeout = (requestedTimeout < TIMEOUT_SERVICE_MAX) ? requestedTimeout : TIMEOUT_SERVICE_MAX;
long tick = (managerTimeout == DETECTION_SHORT) ? TICK_SHORT : TICK_LOOP;
// Guard the service with a countdown timer.
if (countDownTimer != null) {
countDownTimer.cancel();
}
countDownTimer = new CountDownTimer(managerTimeout, tick) {
@Override
public void onTick(long millisUntilFinished) { }
@Override
public void onFinish() {
IndoorOutdoorLogger.d(IndoorOutdoorService.this, TAG, "Timeout reached");
if (countDownTimer != null) {
countDownTimer.cancel();
}
IndoorOutdoorService.this.stopSelf();
IndoorOutdoorLogger.d(IndoorOutdoorService.this, TAG, "Indoor Outdoor Service shut down.");
}
}.start();
if (mode != 0) {
isInLoopMode.set(mode == DETECTION_LOOP);
Thread t = new Thread() {
public void run() {
synchronized (lock) {
if (manager == null) {
manager = new IndoorOutdoorManager(ctx, detectionListener, isInLoopMode.get(), trigger);
}
if (client == null) {
client = new IndoorOutdoorClient(ctx, null);
}
manager.start();
client.startUserActivityRealTimeUpdates();
}
}
};
t.start();
}
}
当我尝试运行应用程序时,出现此异常:
Can't create handler inside thread that has not called Looper.prepare()
异常指向的行是我创建countDownTimer实例的地方。
一些注意事项:
对于 Android N 及以下,流程为:
广播接收器从onStartCommand()
的{{1}}开始,依次运行我的Service
方法,即使在背景中也没有问题。
要调整应用程序使其在 Android O 及更高版本上运行,我必须使用runService()
并将Service更改为JobIntentService以支持后台运行。它导致WorkManager
出现异常,现在我被困住了。