我正在尝试构建一个 Android 应用程序,它将每 10 分钟重复运行一些进程。
我发现 Handlers
比计时器或调度更可靠。因此,我将使用 Handlers
使用下面给出的代码开发我的应用。
我有点担心以下代码会在我每次启动应用程序并保持它们并行运行时创建单独的 Handlers
,可能是因为我正在创建 Handler
在 onCreate
上。
那么一次只在后台运行一个 Handler
的最佳方法是什么?
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler(); // new handler
handler.postDelayed(runnable, 1000*60*10); // 10 mins int.
setContentView(R.layout.activity_pro__sms);
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
/* my set of codes for repeated work */
foobar();
handler.postDelayed(this, 1000*60*10); // reschedule the handler
}
};
最佳答案
您可以扩展 Application 类并在其中完成您的工作。
public class App extends Application {
private Handler handler;
@Override
protected void onCreate() {
super.onCreate();
handler = new Handler(); // new handler
handler.postDelayed(runnable, 1000*60*10); // 10 mins int.
setContentView(R.layout.activity_pro__sms);
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
/* my set of codes for repeated work */
foobar();
handler.postDelayed(this, 1000*60*10); // reschedule the handler
}
};
}
并在 list 中声明你的类:
<application android:name=".App">
已编辑
但它只有在您的应用程序正在运行时才会起作用,否则您可以使用 AlarmManager
。
关于java - 用于重复任务的 Android 处理程序 - 它会重叠吗?定时器任务 VS 处理程序 VS 警报管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190732/