如何让 Android 程序“等待”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11548864/
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
How to make an Android program 'wait'
提问by JuiCe
I want to cause my program to pause for a certain number of milliseconds, how exactly would I do this?
我想让我的程序暂停一定的毫秒数,我到底该怎么做?
I have found different ways such as Thread.sleep( time )
, but I don't think that is what I need. I just want to have my code pause at a certain line for x milliseconds. Any ideas would be greatly appreciated.
我找到了不同的方法,例如Thread.sleep( time )
,但我认为这不是我需要的。我只想让我的代码在某一行暂停 x 毫秒。任何想法将不胜感激。
This is the original code in C...
这是C中的原始代码...
extern void delay(UInt32 wait){
UInt32 ticks;
UInt32 pause;
ticks = TimGetTicks();
//use = ticks + (wait/4);
pause = ticks + (wait);
while(ticks < pause)
ticks = TimGetTicks();
}
wait is an amount of milliseconds
等待是毫秒数
采纳答案by Edward Falk
OK, first of all, never implement a delay with a busy loop as you're doing. I can see where that comes from -- I'm guessing that the palm pilot was a single-process device with no built-in sleep() function, but on a multi-process device, a busy loop like that just brings the entire processor to its knees. It kills your battery, prevents normal system tasks from running properly, slows down other programs or stops them completely, makes the device unresponsive, and can even cause it to get hot in your hands.
好的,首先,永远不要像你在做的那样用繁忙的循环来实现延迟。我可以看到这是从哪里来的——我猜 Palm Pilot 是一个没有内置 sleep() 函数的单进程设备,但在多进程设备上,像这样的繁忙循环只会带来整个处理器跪下。它会耗尽您的电池,阻止正常的系统任务正常运行,减慢其他程序的速度或完全停止它们,使设备无响应,甚至可能导致它在您手中变热。
The call you're looking for is Thread.sleep(). You'll need to set up to catch any interrupt exceptions that occur while you're sleeping.
您正在寻找的调用是 Thread.sleep()。您需要进行设置以捕获在您睡觉时发生的任何中断异常。
Second, with event-based user interfaces such as Android (or pretty much any modern GUI system), you never want to sleep in the UI thread. That will also freeze up the entire device and result in an ANR (Activity Not Responding) crash, as other posters have mentioned. Most importantly, those little freezes totally ruin the user experience.
其次,对于基于事件的用户界面,例如 Android(或几乎任何现代 GUI 系统),您永远不想在 UI 线程中休眠。正如其他海报所提到的,这也会冻结整个设备并导致 ANR(活动无响应)崩溃。最重要的是,那些小的冻结完全破坏了用户体验。
(Exception: if you're sleeping for short enough intervals that the user probably won't notice, you can get away with it. 1/4 second is probably ok, although it can make the application janky depending on the situation.)
(例外:如果您睡眠的时间间隔足够短而用户可能不会注意到,您可以摆脱它。1/4 秒可能没问题,尽管它可能会根据情况使应用程序卡顿。)
Unfortunately, there's no clean and elegant way to do what you want if what you're doing is porting a loop-based application to an event-based system.
不幸的是,如果您正在做的是将基于循环的应用程序移植到基于事件的系统,则没有干净优雅的方式来做您想做的事情。
That said, the proper procedure is to create a handler in your UI thread and send delayed messages to it. The delayed messages will "wake up" your application and trigger it to perform whatever it was going to do after the delay.
也就是说,正确的过程是在您的 UI 线程中创建一个处理程序并向其发送延迟消息。延迟的消息将“唤醒”您的应用程序并触发它执行延迟后要执行的任何操作。
Something like this:
像这样的东西:
View gameBoard; // the view containing the main part of the game
int gameState = 0; // starting
Handler myHandler;
public void onCreate(Bundle oldState) {
super.onCreate(oldState);
...
gameBoard = findViewById(R.layout.gameboard);
myHandler = new Handler();
...
}
public void onResume() {
super.onResume();
displayStartingScreen();
myHandler.postDelayed(new Runnable() {
gotoState1();
}, 250);
}
private void gotoState1() {
// It's now 1/4 second since onResume() was called
displayNextScreen();
myHandler.postDelayed(new Runnable() {
gotoState2();
}, 250);
}
...
回答by FoamyGuy
You really should not sleep the UI thread like this, you are likely to have your application force close with ActivityNotResponding exception if you do this.
您真的不应该像这样使 UI 线程休眠,如果您这样做,您的应用程序可能会因 ActivityNotResponding 异常而强制关闭。
If you want to delay some code from running for a certain amount of time use a Runnable and a Handler like this:
如果您想将某些代码延迟运行一段时间,请使用 Runnable 和 Handler ,如下所示:
Runnable r = new Runnable() {
@Override
public void run(){
doSomething(); //<-- put your code in here.
}
};
Handler h = new Handler();
h.postDelayed(r, 1000); // <-- the "1000" is the delay time in miliseconds.
This way your code still gets delayed, but you are not "freezing" the UI thread which would result in poor performance at best, and ANR force close at worst.
这样您的代码仍然会延迟,但您不会“冻结” UI 线程,这最多会导致性能不佳,最坏的情况是 ANR 强制关闭。
回答by prolink007
Do something like the following. Here is a link to the reference, this might be helpful.
执行以下操作。这是参考的链接,这可能会有所帮助。
final MyActivity myActivity = this;
thread= new Thread(){
@Override
public void run(){
try {
synchronized(this){
wait(3000);
}
}
catch(InterruptedException ex){
}
// TODO
}
};
thread.start();
回答by Mohamad Abdallah
You can use the Handler
class and the postDelayed()
method to do that:
您可以使用Handler
类和postDelayed()
方法来做到这一点:
Handler h =new Handler() ;
h.postDelayed(new Runnable() {
public void run() {
//put your code here
}
}, 2000);
}
2000 ms is the delayed time before execute the code inside the function
2000 ms 是执行函数内部代码之前的延迟时间
回答by Primal Pappachan
Not sure why you want the program to pause. In case you wish to do some task in the background and use the results, look at AsyncTask. I had a similar questionawhile back.
回答by Ken
The SystemClock.sleep(millis) is a utility function very similar to Thread.sleep(millis), but it ignores InterruptedException.
SystemClock.sleep(millis) 是一个与 Thread.sleep(millis) 非常相似的实用函数,但它忽略了 InterruptedException。
回答by rmoore
try {
Thread.sleep(2000); //1000 milliseconds is one second.
}
catch (InterruptedException e)
{
e.printStackTrace();
}
回答by Jon Taylor
I think Thread.sleep(....)probably is what you want you just may not be doing it correctly. What exactly are you trying to pause? Hopefully not the UI thread? Im guessing you have some background thread performing some tasks at some kind of interval? If so then Thread.sleep will put that particular thread to sleep for a certain time, it will not however pause all threads.
我认为Thread.sleep(....)可能是你想要的,你可能没有正确地做。你到底想暂停什么?希望不是 UI 线程?我猜你有一些后台线程以某种间隔执行一些任务?如果是这样,那么 Thread.sleep 将使该特定线程休眠一段时间,但它不会暂停所有线程。