java - 如何在 Android 中制作一个没有新类的简单计时器?

标签 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!!!

    }

}

我该怎么做?现在服务只执行一次 myCycle(),因为我调用了 onStart()。

最佳答案

使用 TimerTimerTask .要每 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/

相关文章:

java - 从 java 执行密码查询 (Neo4j)

android - 通过 PhoneGap Build 从 Android 4.x 应用程序的图像映射区域中删除突出显示

java - 执行时间的计算

forms - VISUAL BASIC 6::使用计时器卸载 Splash 表单

actionscript-3 - 向事件 ActionScript 3 添加定时延迟?

java - setVisibility(View.GONE) 在 Fragment 中不起作用

java - 使用 JUnit 测试 Spring Controller

java - 警告 : Unable to find org. apache.http.lagecy.jar

java - 我如何知道上下文是 Activity 还是 IntentService?

java - 测试时如何在 Controller 内 Autowiring Spring bean?