如何在Android中没有新类的简单计时器?

Lor*_*ork 3 java android timer

我正在开发一个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!!!

    }

}
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?现在服务执行myCycle()一次,因为我在onStart()中调用了一个调用.

dog*_*ane 7

使用带TimerTaskTimer.要每100秒执行一次方法,可以在方法中使用以下方法.请注意,此方法会创建一个新线程.onStart

new Timer().schedule(new TimerTask() {
     @Override
     public void run() {
         myCycle();
     }
}, 0, 100000);
Run Code Online (Sandbox Code Playgroud)

或者,使用本文所述的android.os.Handler:从Timer更新UI.它比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);
Run Code Online (Sandbox Code Playgroud)