2011-07-07 91 views
1

我需要编写一些应用程序,每隔几分钟会做一些背景工作。我的问题是我如何从服务开始这项工作。我是否需要使用线程并使用某些系统实用程序计算时间,或者有更好的解决方案?Android - 每隔几分钟做一次背景工作

回答

1

您可以使用HandlerpostDelayed方法:

Handler handler = new Handler(Looper.getMainLooper()); 
handler.postDelayed(new Runnable() 
    public void run() { 
     // your work 
    } 
}, minutes * 60 * 1000); 

如果设定的时间足够长,你也可以考虑使用AlarmManager

1

(不能似乎添加评论,因此增加一个答案)

,因为这个任务将时间可持续进行,我会延长这样的锡安的例子:

Handler handler = new Handler(Looper.getMainLooper()); 
handler.postDelayed(new Runnable() 
    public void run() { 
    // your work 
    //... 
    handler.postDelayed(this, minutes * 60 * 1000); //this will schedule the task again 
    } 
}, minutes * 60 * 1000); 
相关问题