我下面这个教程有一个载入画面在我的程序。 本教程说我的活动应该使用睡眠()()的命令的睡眠,但它不承认睡眠()的函数,并为我提供了一个错误,问我是否想创建一个名为睡眠()方法。
下面是代码示例:
public class LoadingScreenActivity extends Activity {
//Introduce an delay
private final int WAIT_TIME = 2500;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
//Simulating a long running task
this.Sleep(1000);
System.out.println("Going to Profile Data");
/* Create an Intent that will start the ProfileData-Activity. */
Intent mainIntent = new Intent(LoadingScreenActivity.this,ProfileData.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
}, WAIT_TIME);
}
}
您可以使用folllowing方法之一:
Thread.sleep(timeInMills);
要么
SystemClock.sleep(timeInMills);
SystemClock.sleep(milliseconds)
是一个效用函数非常类似Thread.sleep(milliseconds)
,但它忽略InterruptedException
。 使用此功能的延迟,如果你不使用Thread.interrupt()
因为它会保存线程的中断状态。
您发布的代码是可怕的。 请不要使用在实际设备上。 你会得到一个“应用程序没有响应”如果你运行一些类似的错误。
如果您使用的处理程序,请记住,处理程序是它运行的线程上创建。 因此调用new Handler().post(...
在UI线程将执行在UI线程上可运行的,包括这个“长时间运行的操作。”的好处是,你可以创建一个处理程序,您可以使用UI线程以后,如下图所示。
为了把长时间运行的操作到后台线程,你需要创建一个线程各地可运行,如下图所示。 现在,如果你想更新UI一旦长时间运行的操作完成后,你需要张贴到UI线程,使用处理程序。
注意,此功能是一个再合适不过AsyncTask
这将使得这个看起来比下面的图案更清洁了很多。 不过,我包括在该显示处理程序,线程和的Runnable如何关联。
public class LoadingScreenActivity extends Activity {
//Introduce a delay
private final int WAIT_TIME = 2500;
private Handler uiHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHandler = new Handler(); // anything posted to this handler will run on the UI Thread
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
Runnable onUi = new Runnable() {
@Override
public void run() {
// this will run on the main UI thread
Intent mainIntent = new Intent(LoadingScreenActivity.this,ProfileData.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
};
Runnable background = new Runnable() {
@Override
public void run() {
// This is the delay
Thread.Sleep( WAIT_TIME );
// This will run on a background thread
//Simulating a long running task
Thread.Sleep(1000);
System.out.println("Going to Profile Data");
uiHandler.post( onUi );
}
};
new Thread( background ).start();
}
使用了Thread.sleep(1000);
1000毫秒,该计划将暂停的次数。
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
请记住:使用这个代码是不推荐的,因为它的时间,但没有控制延迟,并可能需要更多或更少的时间。