android timer 导致内存泄漏,android - 使用CountDownTimer会导致RuntimeException - 堆栈内存溢出...
我在我的应用程序中有以下流程在后台运行:OneTimeWorkRequest启动JobIntentService ,而后者又在onHandleWork()方法中调用runService() (我的方法)。private void runService(final Context ctx, final IndoorOutdoorManager.AggregatedDetectionListener
我在我的应用程序中有以下流程在后台运行:
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()一个的Service这反过来会运行我runService()方法,没有任何问题,即使是在研究背景。 要调整应用程序以在Android O及更高版本上运行,我必须使用WorkManager并将服务更改为JobIntentService以支持后台运行。 它导致CountDownTimer异常,现在我被卡住了。
更多推荐
所有评论(0)