spo*_*b92 20 java multithreading android sleep
我正在按照本教程在程序中加载一个屏幕.教程说我的活动应该使用Sleep()命令Sleep(),但是它不能将Sleep()识别为函数并向我提供错误,询问我是否要创建一个名为Sleep()的方法.
这是代码示例:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Kar*_*ana 48
您可以使用以下方法之一:
Thread.sleep(timeInMills);
Run Code Online (Sandbox Code Playgroud)
要么
SystemClock.sleep(timeInMills);
Run Code Online (Sandbox Code Playgroud)
SystemClock.sleep(milliseconds)是一个非常类似的实用函数Thread.sleep(milliseconds),但它忽略了InterruptedException.如果不使用Thread.interrupt(),请使用此函数进行延迟,因为它将保留线程的中断状态.
你发布的代码太可怕了.请不要在实际设备上使用它.如果您运行与此类似的操作,您将收到"应用程序无响应"错误.
如果您正在使用处理程序,请记住在运行它的线程上创建了一个处理程序.因此,调用new Handler().post(...UI线程将在UI线程上执行runnable,包括这个"长时间运行的操作".优点是您可以为UI线程创建一个Handler,稍后您可以使用它,如下所示.
要将长时间运行的操作放入后台线程,您需要在runnable周围创建一个Thread,如下所示.现在,如果要在长时间运行的操作完成后更新UI,则需要使用处理程序将其发布到UI线程.
请注意,此功能非常适合使用此功能AsyncTask,使其看起来比下面的模式更清晰.但是,我将其包括在内以显示Handler,Threads和Runnables如何相关.
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79266 次 |
| 最近记录: |