简体   繁体   English

如何设置计时器以运行功能中的其他活动? Android应用

[英]How to set a timer to run another activity in a function? Android app

I want the toast message to display(if clicked on the right answer), but not go to the next activity directly. 我希望显示吐司消息(如果单击正确的答案),但不直接进入下一个活动。 So i want to set a timer for like 2 seconds so the user can easily read it, and then go to the next activity. 所以我想将计时器设置为2秒钟,以便用户可以轻松阅读它,然后转到下一个活动。 What is wrong with this code? 此代码有什么问题?

public void rightAnsnextQ (View view)  
{  
    Intent intent = new Intent(this, ThirdQuestion.class);


    Toast.makeText(this, "Good job", Toast.LENGTH_SHORT).show();  

    Thread.sleep(2000);

    startActivity(intent);

}

You are calling sleep on the ui thread which is wrong. 您正在ui线程上调用sleep,这是错误的。 It blocks the ui thread. 它阻止ui线程。 You should never block the ui thread. 您永远不应阻塞ui线程。

 Thread.sleep(2000); // remove this

Instead use Handler postDelayed with a delay of 2 seconds 而是使用Handler postDelayed延迟2秒

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
 public void run() {
     // do something
     Intent intent = new Intent(ActivityName.this, ThirdQuestion.class);
     // If you just use this that is not a valid context. Use ActivityName.this
     startActivity(intent);
   }
}, 2000);

try below code:- 尝试下面的代码:-

private final int interval = 1000; // 1 Second
private Handler handler = new Handler();
Private Runnable runnable = new Runnable(){
    public void run() {
        Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
    }
};


handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

see below link for more info:- 有关更多信息,请参见下面的链接:-

How to set a timer in android 如何在Android中设置计时器

try this, 尝试这个,

  public void rightAnsnextQ (View view)  {

       Toast.makeText(this, "Good job", Toast.LENGTH_SHORT).show();  


        new Handler().postDelayed(new Runnable() {

          @Override
         public void run() {

        Intent intent = new Intent(this, ThirdQuestion.class);
                startActivity(intent);



            }

           }, 100);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM