如何使无的Android新类一个简单的计时器? [英] How to make a simple timer without new class in Android?
问题描述
我在开发Android服务,必须在后台运行,执行一个函数中的每个100秒。这就是源$ C $ C(例如)
I'm developing a Service for Android, that must run in background, executing a function each 100 seconds. That's the source code (example)
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()。
How I can do that? Now the service execute myCycle() just one time, beacause I put a calling in onStart().
推荐答案
使用一个定时器与的TimerTask 的。要执行你的方法每隔100秒,你可以用你的在onStart
方法如下。请注意,此方法创建一个新的线程。
Use a Timer with a TimerTask. To execute your method every 100 seconds, you can use the following in your onStart
method. Be aware that this method creates a new thread.
new Timer().schedule(new TimerTask() {
@Override
public void run() {
myCycle();
}
}, 0, 100000);
另外,使用 android.os.Handler 这篇文章中所述:<一HREF =http://developer.android.com/resources/articles/timed-ui-updates.html>从定时器更新UI。它比定时器更好,因为它在主线程运行,避免第二线程的开销
Alternatively, use an android.os.Handler as described in this article: Updating the UI from a Timer. It is better than a Timer because it runs in the main thread, avoiding the overhead of a second thread.
private Handler handler = new Handler();
Runnable task = new Runnable() {
@Override
public void run() {
myCycle();
handler.postDelayed(this, 100000);
}
};
handler.removeCallbacks(task);
handler.post(task);
这篇关于如何使无的Android新类一个简单的计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!