我主要活動:安卓:ProgressDialog外部異步類(某塊異步線程)
public class ChooseWriteSentenceActivity extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String userName = "Zdzisiu";
String password = "Ziemniak";
MainServie service = new MainService(this);
boolean isExsist = service.findUser(String userName, String password);
//more code...
}
}
在我的應用程序服務使用存儲庫和jsonconsumers但簡單的代碼,我跳過他們。
public class MyService{
private Context context;
public MyService(Context context){
this.context = context
}
public boolean findUser(String userName, String password){
String resultS = null;
try{
resultS = new QueryExecutorFindUser(context).execute(userName,password).get();
}
catch(Exception ex){
ex.printStackTrace();
}
boolean realRes = jsonConsumer(resultS).getFindUser();
return realRes;
}
}
public class QueryExecutorFindUser extends AsyncTask<String,Void,String> {
protected final String connectionUrl = "http://myWebService:44302/Service.svc/";
protected ProgressDialog progressDialog;
protected Context curContext;
public QueryExecutor(Context context){
curContext = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(curContext,"Loading...",
"Loading application View, please wait...", false, false);
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
}
protected String doInBackground(String... args){
String result = null;
String url = connectionUrl + args[0] + "/" + args[1];
HttpResponse response = null;
HttpClient httpclient = this.getNewHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
try{
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
if(response != null){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
result = out.toString();
}
} else{
throw new IOException(statusLine.getReasonPhrase());
}
} catch(Exception ex){
ex.getMessage();
} finally{
if(response != null){
try{
response.getEntity().getContent().close();
} catch(Exception ex){
}
}
}
return result;
}
}
而且進度對話框顯示,但只有後onCreatre在ChooseWriteSentenceActivity包括QueryExecutor doInBacground(...)的所有代碼完成(所以它在同一時間幾乎消失)。它看起來像......等待與QueryExecutorFindUser.doInBackground()線程,它是像同步運行(?),我認爲,因爲當我調試代碼onPreExecute()正確運行(並開始之前doInBackground(...))和progressDialog如果我從QueryExecutorFindUser中刪除擴展AsyncTask,並在主要活動中使用此擴展創建私有類(並從包含服務的onCreated()運行所有代碼。).isShowing()== true(但屏幕上不顯示:()在這個私人的類.doInBackground(...))findUser()它工作okey。
我更喜歡progressDialog在一個地方沒有在所有主要活動(實踐中的cource的使用QueryExecutor所有查詢不僅findUser)我不知道我做錯了什麼,我花了整整一天的時間沒有結果:(
嘗試在onCreate而不是onPre上啓動進度對話框 – 2014-12-05 14:52:16
謝謝,但它沒有幫助 – user3232354 2014-12-05 16:37:37