Java 如何在Android延迟后调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3072173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:13:30  来源:igfitidea点击:

How to call a method after a delay in Android

javaandroidhandlerdelay

提问by aryaxt

I want to be able to call the following method after a specified delay. In objective c there was something like:

我希望能够在指定的延迟后调用以下方法。在目标 c 中有类似的东西:

[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];

Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.

android 中是否有与 java 相同的方法?例如,我需要能够在 5 秒后调用一个方法。

public void DoSomething()
{
     //do something here
}

采纳答案by kontinuity

Kotlin

科特林

Handler().postDelayed({
  //Do something after 100ms
}, 100)



Java

爪哇

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 100ms
  }
}, 100);



回答by Nate

I suggest the Timer, it allows you to schedule a method to be called on a very specific interval. This will not block your UI, and keep your app resonsive while the method is being executed.

我建议使用Timer,它允许您安排在非常特定的时间间隔内调用的方法。这不会阻塞您的 UI,并在执行方法时保持您的应用程序响应。

The other option, is the wait();method, this will block the current thread for the specified length of time. This will cause your UI to stop responding if you do this on the UI thread.

另一个选项是wait(); 方法,这将阻塞当前线程指定的时间长度。如果您在 UI 线程上执行此操作,这将导致您的 UI 停止响应。

回答by OscarRyz

See this demo:

看这个演示:

import java.util.Timer;
import java.util.TimerTask;

class Test {
     public static void main( String [] args ) {
          int delay = 5000;// in ms 

          Timer timer = new Timer();

          timer.schedule( new TimerTask(){
             public void run() { 
                 System.out.println("Wait, what..:");
              }
           }, delay);

           System.out.println("Would it run?");
     }
}

回答by erickson

Note:This answer was given when the question didn't specify Android as the context. For an answer specific to the Android UI thread look here.

注意:当问题没有将 Android 指定为上下文时,给出了这个答案。有关特定于 Android UI 线程的答案,请查看此处。



It looks like the Mac OS API lets the current thread continue, and schedules the task to run asynchronously. In the Java, the equivalent function is provided by the java.util.concurrentpackage. I'm not sure what limitations Android might impose.

看起来 Mac OS API 让当前线程继续运行,并安排任务异步运行。在 Java 中,java.util.concurrent包提供了等效的功能。我不确定 Android 可能会施加哪些限制。

private static final ScheduledExecutorService worker = 
  Executors.newSingleThreadScheduledExecutor();

void someMethod() {
  ?
  Runnable task = new Runnable() {
    public void run() {
      /* Do something… */
    }
  };
  worker.schedule(task, 5, TimeUnit.SECONDS);
  ?
}

回答by aryaxt

Thanks for all the great answers, I found a solution that best suits my needs.

感谢所有出色的答案,我找到了最适合我需求的解决方案。

Handler myHandler = new DoSomething();
Message m = new Message();
m.obj = c;//passing a parameter here
myHandler.sendMessageDelayed(m, 1000);

class DoSomething extends Handler {
    @Override
    public void handleMessage(Message msg) {
      MyObject o = (MyObject) msg.obj;
      //do something here
    }
}

回答by Vishnu

final Handler handler = new Handler(); 
Timer t = new Timer(); 
t.schedule(new TimerTask() { 
    public void run() { 
        handler.post(new Runnable() { 
            public void run() { 
                //DO SOME ACTIONS HERE , THIS ACTIONS WILL WILL EXECUTE AFTER 5 SECONDS...
            }
        }); 
    } 
}, 5000); 

回答by Jules Colle

I couldn't use any of the other answers in my case. I used the native java Timer instead.

在我的情况下,我无法使用任何其他答案。我改用了本机 java Timer 。

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {
        // this code will be executed after 2 seconds       
    }
}, 2000);

回答by Hossam Ghareeb

you can use Handler inside UIThread:

你可以在 UIThread 中使用 Handler:

runOnUiThread(new Runnable() {

    @Override
    public void run() {
         final Handler handler = new Handler();
         handler.postDelayed(new Runnable() {
           @Override
           public void run() {
               //add your code here
           }
         }, 1000);

    }
});

回答by Faakhir

A suitable solution in android:

android中的一个合适的解决方案:

private static long SLEEP_TIME = 2 // for 2 second
.
.
MyLauncher launcher = new MyLauncher();
            launcher.start();
.
.
private class MyLauncher extends Thread {
        @Override
        /**
         * Sleep for 2 seconds as you can also change SLEEP_TIME 2 to any. 
         */
        public void run() {
            try {
                // Sleeping
                Thread.sleep(SLEEP_TIME * 1000);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
            //do something you want to do
           //And your code will be executed after 2 second
        }
    }

回答by pomber

For executing something in the UI Thread after 5 seconds:

在 5 秒后在 UI 线程中执行某些内容:

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something here
    }
}, 5000);