[英]How to waits the thread till another thread completes
我想在網格視圖中加載圖像時顯示進度對話框。
我面臨的問題是當前線程和Progress Dialog線程同時運行。
public String Method1(){
String output="";
final ProgressDialog aProgDialogL = ProgressDialog.show(this, "", "Loading...");
Thread thread = new Thread() {
public void run () {
//My codes
aHandlerL.post(new Runnable() {
@Override
public void run() {
//Post Runnable codes
aProgDialogL.dismiss();
}
});
}
};
thread.start();
/*
*
*
* OTHER CODES
*
*
*/
return output;
}
在上面的例子中,我需要在Progress Dialog Thread中運行代碼。 完成執行后,我需要運行我的“其他代碼”。 怎么做?
。
我嘗試使用Async任務。 在異步任務完成之前,method1被取消並重新生成字符串。
public String Method1(){
String result="";
new GetImages().execute();
return result;
}
public class GetData extends AsyncTask<Void, Void, Integer>{
@Override
protected void onPreExecute() {
aProgDialogL = ProgressDialog.show(Main.this, "", "Loading...");
}
@Override
protected Integer doInBackground(Void... params) {
//Progress Dialig Code
return null;
}
@Override
protected void onPostExecute(Integer result) {
aProgDialogL.dismiss();
//OTHER CODES
super.onPostExecute(result);
}
}
您可以使用Async任務。 http://developer.android.com/reference/android/os/AsyncTask.html 。 這里有一個很好的教程。 http://www.vogella.com/articles/AndroidPerformance/article.html 。 另請查看此鏈接http://developer.android.com/guide/components/processes-and-threads.html 。 使用asynctask根據您的需要修改它。
doInBackground()- For long running operations. Don't update ui here.
onPreExecute()- update ui before running the operatio nin background.
onPostExecute()- update ui after running the operation.
我建議你采取一些不同的方法。
不要涉及Method1()函數中的任何線程。你的Method1()函數應該在單獨的線程下運行。
以下代碼段將為您提供幫助。
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.btnPopup))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new Thread() {
public void run() {
String answer = Method1();
runOnUiThread(new Runnable() {
@Override
public void run() {
// Here you will write the code which is
// to be executed on main thread.
}
});
};
}.start();
}
});
}
public String Method1() {
// Write code
return "result";
}
}
我建議使用AsyncTask來解決你的問題
http://p-xr.com/merging-2-tutorials-xml-data-progressdialog-using-asynctask/
http://p-xr.com/android-tutorial-how-to-make-a-progress-dialog/
和
http://developer.android.com/reference/android/os/AsyncTask.html
而不是那樣:如何使用Timer在特定時間之后停止你的線程並在stop語句之后編寫你想要的代碼那樣:
Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
thread.stop;
// Other code }
,你想要的時間);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.