这是如何安排 java 方法在 1 秒后运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6205210/
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
Is this how to schedule a java method to run 1 second later?
提问by djcouchycouch
In my method, I want to call another method that will run 1 second later. This is what I have.
在我的方法中,我想调用另一个将在 1 秒后运行的方法。这就是我所拥有的。
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
MyMethod();
Log.w("General", "This has been called one second later");
timer.cancel();
}
}, 1000);
Is this how it's supposed to be done? Are there other ways to do it since I'm on Android? Can it be repeated without any problems?
这是应该如何完成的吗?因为我在 Android 上,还有其他方法可以做到吗?是否可以毫无问题地重复?
回答by inazaruk
There are several alternatives. But here is Android specific one.
有几种选择。但这里是 Android 特定的。
If you thread is using Looper
(and Normally all Activity
's, BroadcastRecevier
's and Service
's methods onCreate
, onReceive
, onDestroy
, etc. are called from such a thread), then you can use Handler
. Here is an example:
如果线程使用Looper
(和通常所有的Activity
年代,BroadcastRecevier
年代和Service
的方法onCreate
,onReceive
,onDestroy
等都是从这样一个线程调用),那么你可以使用Handler
。下面是一个例子:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
myMethod();
}
}, 1000);
Note that you do not have to cancel anything here. This will be run only once on the same thread your Handler was created.
请注意,您不必在此处取消任何内容。这将仅在创建处理程序的同一线程上运行一次。
回答by mre
Instead of a Timer
, I'd recommend using a ScheduledExecutorService
而不是Timer
,我建议使用ScheduledExecutorService
final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.schedule(new Runnable(){
@Override
public void run(){
MyMethod();
}
}, 1, TimeUnit.SECONDS);
回答by Snicolas
If you are notin UI thread, consider adding a very simple:
如果你不在UI 线程中,可以考虑添加一个非常简单的:
try
{
Thread.sleep( 1000 );
}//try
catch( Exception ex)
{ ex.printStackTrace(); }//catch
//call your method
回答by Paul Verest
ScheduledExecutorService or AsyncTask for UI related.
与 UI 相关的 ScheduledExecutorService 或 AsyncTask。
Note that if you are to update UI, that code should be posted to UI thread. as in Processes and ThreadsGuide
请注意,如果您要更新 UI,则应将该代码发布到 UI 线程。如进程和线程指南
final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
There is also nice postDelayed
method in View
里面也有不错的postDelayed
方法View
mImageView.postDelayed(new Runnable(){
@Override
public void run() {
mImageView.setImageResource(R.drawable.ic_inactive);
}
}, 1000);
that will update UI after 1 sec.
这将在 1 秒后更新 UI。