TimerTask突然停止执行

时间:2016-03-29 09:43:22

标签: java android service timertask

我的应用程序有一个T_Service,它有一个TimerTask类,B_TimerTask以固定的时间间隔捆绑数据并将其上传到数据库。

B_TimerTask

class B_TimerTask extends TimerTask {
    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Override
    public void run() {


        // run on another thread
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                try {
                      //  Do the task of uploading to DB.

                    }
                } catch (RuntimeException e) {
                    //Log the exception
                } catch (Throwable e) {
                    //Log the message of e
                    throw e;
                }
            }
        });
    }
}

onStartCommand()的{​​{1}}中,我将T_Service安排为

B_TimerTask

经过测试(多次),我发现计时器任务在某段时间(约26分钟)后停止执行,我在 private Timer mTimer = new Timer(); mTimer.scheduleAtFixedRate(new B_TimerTask(), 0, NOTIFY_INTERVAL); 上看到警告

LogCat

我不确定如何纠正这个问题,并猜测Handler的泄漏可能会导致TimerTask的停止。此外,在仔细检查Android Studio上手机的内存使用情况(Allocated vs Free memory)时,内存释放速度比为进程分配的内存慢。所以我猜测可能存在内存泄漏。 我想知道如何避免这种泄漏或更好的方法来实现这个功能。

感谢您的帮助。

0 个答案:

没有答案