我正在为 Android 开发一个服务,它必须在后台运行,每 100 秒执行一个函数。这是源代码(例子)
package com.example
import ....
public class Servizio extends Service {
public IBinder onBind(Intent intent) {
}
public void onCreate() {
}
public void onDestroy() {
//here put the code that stop the timer cycle
}
public void onStart(Intent intent, int startid) {
//i want to begin here the timercycle that each 100 s call myCycle()
}
public void myCycle() {
//code that i can't move on other class!!!
}
}
我该怎么做?现在服务只执行一次 myCycle(),因为我调用了 onStart()。
最佳答案
使用 Timer用TimerTask .要每 100 秒执行一次您的方法,您可以在 onStart
方法中使用以下内容。请注意,此方法会创建一个新线程。
new Timer().schedule(new TimerTask() {
@Override
public void run() {
myCycle();
}
}, 0, 100000);
或者,使用 android.os.Handler如本文所述:Updating the UI from a Timer .它比 Timer 更好,因为它在主线程中运行,避免了第二个线程的开销。
private Handler handler = new Handler();
Runnable task = new Runnable() {
@Override
public void run() {
myCycle();
handler.postDelayed(this, 100000);
}
};
handler.removeCallbacks(task);
handler.post(task);
关于java - 如何在 Android 中制作一个没有新类的简单计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7433334/