Java Android中5秒后执行函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31041884/
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-11 10:33:58  来源:igfitidea点击:

Execute function after 5 seconds in Android

javaandroidtimer

提问by Jishad

I am new in android development and now my launcher activity show only 5 seconds and after that I want to check the user is logged in or not function and perform the actions.

我是 android 开发的新手,现在我的启动器活动只显示 5 秒,之后我想检查用户是否登录或未运行并执行操作。

here is my code.

这是我的代码。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    exactPreferences = getSharedPreferences("ExactPreference",MODE_PRIVATE);
    setContentView(R.layout.activity_landing_page);

    session = exactPreferences.getString(Model.getSingleton().SHARED_SESSION_ID,null);
    Log.i("Session Id",session);
        displayData(); // I want to perform this function after 5 seconds.
}


private void displayData() {
    if(session.equals("")){
        Intent loginIntent = new Intent(LandingPage.this,
                LoginActivity.class);
        startActivity(loginIntent);
        Log.i("User Logged In", "False");
    }
    else
    {
        Intent objIntent = new Intent(LandingPage.this,
                IndexPageActivity.class);
        startActivity(objIntent);
        Log.i("User Logged In", "True");
    }

}

采纳答案by Kartheek

You can use the Handler to add some delay.Call the method displayData()as below so that it will be executed after 5 seconds.

您可以使用 Handler 来添加一些延迟。调用如下方法displayData(),使其在 5 秒后执行。

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
          displayData();
        }
    }, 5000);

Note :Do not use the threads like Thread.sleep(5000);because it will block your UI and and makes it irresponsive.

注意:不要使用线程, Thread.sleep(5000);因为它会阻塞您的 UI 并使其无响应。

回答by Phant?maxx

Use a CountDownTimer

使用倒数计时器

// There's a TextView txtCount in Main Activity

final int secs = 5;
new CountDownTimer((secs +1) * 1000, 1000) // Wait 5 secs, tick every 1 sec
{
    @Override
    public final void onTick(final long millisUntilFinished)
    {
        txtCount.setText("" + (int) (millisUntilFinished * .001f));
    }
    @Override
    public final void onFinish()
    {
        txtCount.setText("GO!");
        finish();
        // Time's up - Start the Login Activity
        final Intent tnt =
            new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(tnt);
    }
}.start();

回答by bongo

Try this, code create CountDownTimer with one tick

试试这个,代码一键创建 CountDownTimer

timer = new CountDownTimer(5000, 5000)
{
    public void onTick(long millisUntilFinished)
    {
    }

    public void onFinish()
    {
        displayData();
    }
};
timer.start();

回答by mushahid

Assign millisDelayTimevariable with the milliseconds you desire to cause a delay. mActivityis an object of Activityfor providing Application Context. In your case millisDelayTimeshould be initialized with 5000

使用您希望导致延迟的毫秒数分配millisDelayTime变量。mActivityActivity 的一个对象,用于提供 Application Context。在您的情况下,millisDelayTime应初始化为 5000

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

回答by Jorgesys

The best option to achieve this is using a Handler:

实现这一目标的最佳选择是使用Handler

 int TIME = 5000; //5000 ms (5 Seconds)

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

               function(); //call function!

            }
        }, TIME);

回答by fazeel zama

long delay = 1000;
long period = 50000;
Timer task = new Timer();
task.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        getDriver(sessionManager.getKEY(), ride_id);
    }
}, delay, period);

回答by franzesz

When possible, try to avoid using postDelayed. It is a bad practice, since it can lose the reference to the objects that you want to draw on your screen and cause a NPE. Use a Handler instead. First of all, create a global variable Handler in which you will have to "handle" the logic for your code. Do so by using the function handleMessage.

如果可能,尽量避免使用 postDelayed。这是一种不好的做法,因为它可能会丢失对您要在屏幕上绘制的对象的引用并导致 NPE。改用处理程序。首先,创建一个全局变量 Handler,您必须在其中“处理”代码的逻辑。通过使用函数handleMessage 来实现。

Handler  handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        if(msg.what == 1){
            // your code here
        }
    }
};       

Then, wherever you want to execute it, just call the function:

然后,无论您想在哪里执行它,只需调用该函数:

// 1 is the ID of your process
handler.sendEmptyMessageDelayed(1, 5000);

Please remember that in the onDestroyView method (in a Fragment) or the onDestroy (in an Activity) you will have to call

请记住,在 onDestroyView 方法(在片段中)或 onDestroy(在活动中)中,您必须调用

    handler.removeMessages(1)

回答by GDNarvaez

For kotlin way

对于 kotlin 方式

Handler().postDelayed({
        //do something
    }, 5000)