Android 上的 setTimeOut() 相当于什么?

发布于 2024-12-25 05:21:58 字数 150 浏览 1 评论 0原文

我需要 Android 的 setTimeOut(call function(),milliseconds); 的等效代码。

setTimeOut(call function(),milliseconds);

I need the equivalent code of setTimeOut(call function(),milliseconds); for android.

setTimeOut(call function(),milliseconds);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

白云不回头 2025-01-01 05:21:58

您可能想查看 TimerTask

既然您再次提出了这个问题,我'我想提出一个不同的建议,即 Handler。它比 TimerTask 使用起来更简单,因为您不需要显式调用 runOnUiThread,因为 Handler 只要在 UI 线程上创建,或者您在其构造函数中使用主循环器创建它,就会与 UI 线程关联。它会像这样工作:

private Handler mHandler;
Runnable myTask = new Runnable() {
  @Override
  public void run() {
     //do work
     mHandler.postDelayed(this, 1000);
  }
}

@Override
public void onCreate(Bundle savedState) {
  super.onCreate(savedState);
  mHandler = new Handler(Looper.getMainLooper());
}
//just as an example, we'll start the task when the activity is started
@Override
public void onStart() { 
  super.onStart();
  mHandler.postDelayed(myTask, 1000);
}

//at some point in your program you will probably want the handler to stop (in onStop is a good place)
@Override
public void onStop() {
  super.onStop();
  mHandler.removeCallbacks(myTask);
}

您的 Activity 中的处理程序需要注意一些事项:

  1. 如果您不在 onStop 中停止它(如果您启动了它,则在 onPause 中不停止它),当您的处理程序仍在运行时,您的 Activity 可能会关闭/不可见在 onResume 中),如果您尝试更新 UI,这将导致问题。
  2. 如果您的手机进入深度睡眠状态,则处理程序不会像您指定的那样频繁触发。我知道这一点,因为我已经使用蓝牙设备进行了一些广泛的测试,以在运行多个小时后测试连接性,并且每次触发时我都使用了处理程序和日志打印。
  3. 如果您需要此计时器持续运行,我建议将其放入比活动持续时间更长的服务中。向服务注册您的活动(通过实现服务中定义的用于与服务通信的接口)。

You probably want to check out TimerTask

Since you brought up this again I'd like to make a different recommendation, which is a Handler. It is simpler to use than a TimerTask as you won't need to explicitely call runOnUiThread as the Handler will be associated with the UI thread so long as it's created on the UI thread or you create it using the main looper in it's constructor. It would work like this:

private Handler mHandler;
Runnable myTask = new Runnable() {
  @Override
  public void run() {
     //do work
     mHandler.postDelayed(this, 1000);
  }
}

@Override
public void onCreate(Bundle savedState) {
  super.onCreate(savedState);
  mHandler = new Handler(Looper.getMainLooper());
}
//just as an example, we'll start the task when the activity is started
@Override
public void onStart() { 
  super.onStart();
  mHandler.postDelayed(myTask, 1000);
}

//at some point in your program you will probably want the handler to stop (in onStop is a good place)
@Override
public void onStop() {
  super.onStop();
  mHandler.removeCallbacks(myTask);
}

There are some things to be aware of with handlers in your activity:

  1. Your activity can be shutdown/non visible while your handler is still running if you don't stop it in onStop (or onPause if you started it in onResume), this will lead to problems if you try to update the UI
  2. If your phone goes into deep sleep the handlers won't fire as often as you have specified. I know this as I've done some extensive testing with bluetooth devices to test connectivity after many hours of operation and I had used handlers along with log prints every time they fired.
  3. If you need this timer to be ongoing I recommend putting it in a service which will last longer than an activity. Register your activity with the service(by implementing an interface defined in the service for communication with the service).
不奢求什么 2025-01-01 05:21:58

这是我在当前项目中使用的代码。正如马特所说,我使用了 TimerTask。
60000 是毫秒。 = 60 秒我用它来刷新比赛比分。

private void refreshTimer() {
        autoUpdate = new Timer();
        autoUpdate.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        adapter = Score.getScoreListAdapter(getApplicationContext());
                        adapter.forceReload();
                        setListAdapter(adapter);
                    }
                });
            }
        }, 0, 60000);

This is the code that i used in my current project. I used TimerTask as Matt said.
60000 is the milisec. = 60 sec. i used it to refresh match scores.

private void refreshTimer() {
        autoUpdate = new Timer();
        autoUpdate.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        adapter = Score.getScoreListAdapter(getApplicationContext());
                        adapter.forceReload();
                        setListAdapter(adapter);
                    }
                });
            }
        }, 0, 60000);
⒈起吃苦の倖褔 2025-01-01 05:21:58

underscore-java 库中有 setTimeout() 方法。

代码示例:

import com.github.underscore.U;
import java.util.function.Supplier;

public class Main {

    public static void main(String[] args) {
        final Integer[] counter = new Integer[] {0};
        Supplier<Void> incr =
                () -> {
                    counter[0]++;
                    return null;
                };
        U.setTimeout(incr, 100);
    }
}

该函数将在 100 毫秒内使用新线程启动。

There is setTimeout() method in underscore-java library.

Code example:

import com.github.underscore.U;
import java.util.function.Supplier;

public class Main {

    public static void main(String[] args) {
        final Integer[] counter = new Integer[] {0};
        Supplier<Void> incr =
                () -> {
                    counter[0]++;
                    return null;
                };
        U.setTimeout(incr, 100);
    }
}

The function will be started in 100 ms with a new thread.

凉栀 2025-01-01 05:21:58

作为使用 java 下划线的 Valentyn 答案的延续:

将依赖项添加到 gradle:

dependencies {
    compile group: 'com.github.javadev', name: 'underscore', version: '1.15'
}

Java:

import com.github.underscore.lodash.$;

$.setTimeout(new Function<Void>() {
    public Void apply() {
        // work
        return null;
    }
}, 1000); // 1 second

As a continuation to Valentyn answer using java underscore:

Add dependency to gradle:

dependencies {
    compile group: 'com.github.javadev', name: 'underscore', version: '1.15'
}

Java:

import com.github.underscore.lodash.$;

$.setTimeout(new Function<Void>() {
    public Void apply() {
        // work
        return null;
    }
}, 1000); // 1 second
不爱素颜 2025-01-01 05:21:58

考虑到现在您可以访问 Kotlin,比处理 Java Thread 更符合 Android 风格的方式是使用 Android Looper,

Handler(Looper.getMainLooper()).postDelayed({ /* action */ }, 2000)

或者,使用 androidx.core:core 更符合 Kotlin 风格的方式-ktx 的 Kotlin 扩展,然后,

import androidx.core.os.postDelayed

Handler(Looper.getMainLooper()).postDelayed(2000) {
    // action
}

您可以使用 TimeUnit.SECONDS.toMillis(2) 代替 2000

More Android-ish way than dealing with Java Thread is to use Android Looper, considering now you have access to Kotlin,

Handler(Looper.getMainLooper()).postDelayed({ /* action */ }, 2000)

Or, the more Kotlin-ish way to to use androidx.core:core-ktx's Kotlin extensions and then,

import androidx.core.os.postDelayed

Handler(Looper.getMainLooper()).postDelayed(2000) {
    // action
}

You can use TimeUnit.SECONDS.toMillis(2) instead 2000.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文