建议更好的线程处理方法

时间:2014-10-25 17:24:37

标签: java android

请查看步骤1& 2如果approch是正确的。另外,建议如何编写第2步。

问题陈述:

1。启动一个持续的线程来捕获应用程序的状态。

Thread thread = new Thread() {
    public void run() {
        while (true) {
            try {
                checkStaus();
                Thread.sleep(TIMER); // 1 mins
            } catch (InterruptedException e) {
                Log.e("MyService", "local Thread error", e);
            }
        }
    }
};
thread.start();

2。通过10分钟后,将捕获的日志发送到服务器。

伪:

一个。保持计数器直到达到600000毫秒(10分钟)

湾启动异步任务以将捕获的日志发送到服务器。

℃。成功发送文件后,重置计数器;空日志文件并继续捕获日志。

由于

2 个答案:

答案 0 :(得分:0)

  1. 绝对没有办法结束你的线程。在您的Activity被杀死后,它将继续循环LONG。因为它也是一个内部类,它将引用你的死活动引起相当大的内存泄漏。

    • 修复: 删除while(true)并将其替换为类似while(isRunning)的布尔值。在isRunning
    • 中将onDestroy()设为false
  2. 更好的方法可能是使用IntentService代替AsyncTaskIntentService是一个非常方便的工具,适用于此类事情。您可以将计时器设置为每10分钟运行一次,然后启动IntentService将日志发送到服务器。它将在后台运行,如果用户离开应用程序,您不必担心它会被系统转储或内存泄漏。

  3. 您唯一需要担心的是文件在发送之前不会被删除。你可以做的就是每次都有一个新文件。所以它会是这样的:

    Write logs to `File1`
    At ten minutes, start `IntentService`.  Pass the name of the file in the `Intent` used to start it`
    Start writing logs to `File2`
    

    IntentService

    Get file name for file to send in the Intent
    Send file to server
    On completion, delete file
    

答案 1 :(得分:0)

使用TimerTask,如下所示:

Timer timer = new Timer();
TimerTask task = new TimerTask() {
    public void run() {
        // ... stuff
        boolean run_again = ???  /// end infinite loop or not .. you should set this somewhere
        if (run_again)
           timer.schedule(this, 600000);
    }
}
timer.schedule(task, 600000); // or 0 if you want to run it right away first

语法可能有点偏离内存

相关问题