[英]How to set a timer to run another activity in a function? Android app
我希望显示吐司消息(如果单击正确的答案),但不直接进入下一个活动。 所以我想将计时器设置为2秒钟,以便用户可以轻松阅读它,然后转到下一个活动。 此代码有什么问题?
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);
}
您正在ui线程上调用sleep,这是错误的。 它阻止ui线程。 您永远不应阻塞ui线程。
Thread.sleep(2000); // remove this
而是使用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);
尝试下面的代码:-
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);
有关更多信息,请参见下面的链接:-
尝试这个,
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.