android timer 导致内存泄漏,android - 使用CountDownTimer会导致RuntimeException - 堆栈内存溢出...

我在我的应用程序中有以下流程在后台运行:

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值