[英]AsyncTask, HttpClient and ProgressDialog
我正在創建一個AsyncTask來將用戶登錄到服務器。 登錄工作正常,但是ProgressDialog直到過程結束才顯示。 用戶點擊按鈕后,UI就會凍結,並且我的對話框不會顯示。
我感謝任何幫助。 這是我的代碼。
public class MyApp extends Activity {
private ProgressDialog dialogo = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button loginButton = (Button) findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String webAddress = preferencias.getString("webAddress", "");
if (webAddress.isEmpty()) {
Toast.makeText(getBaseContext(), "Please, configure a Web Address.", Toast.LENGTH_LONG).show();
} else {
EditText edtUsername = (EditText) findViewById(R.id.edtUsername);
EditText edtPassword = (EditText) findViewById(R.id.edtPassword);
HashMap<String, String> parametros = new HashMap<String, String>();
parametros.put("username", edtUsername.getText().toString());
parametros.put("password", edtPassword.getText().toString());
Requisicao requisicao = new Requisicao(parametros);
AsyncTask<String, Void, String> resposta = requisicao.execute(webAddress + "/login");
try {
Toast.makeText(getBaseContext(), resposta.get(), Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
Toast.makeText(getBaseContext(), "InterruptedException (login)", Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(getBaseContext(), "ExecutionException (login)", Toast.LENGTH_LONG).show();
}
}
}
});
ImageView engrenagem = (ImageView) findViewById(R.id.imgEngrenagem);
engrenagem.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent preferenciasActivity = new Intent(getBaseContext(), Preferencias.class);
startActivity(preferenciasActivity);
}
});
}
public class Requisicao extends AsyncTask<String, Void, String> {
private final HttpClient clienteHttp = new DefaultHttpClient();
private String resposta;
private HashMap<String, String> parametros = null;
public Requisicao(HashMap<String, String> params) {
parametros = params;
}
@Override
protected void onPreExecute() {
dialogo = new ProgressDialog(MyApp.this);
dialogo.setMessage("Aguarde...");
dialogo.setTitle("Comunicando com o servidor");
dialogo.setIndeterminate(true);
dialogo.setCancelable(false);
dialogo.show();
}
@Override
protected String doInBackground(String... urls) {
byte[] resultado = null;
HttpPost post = new HttpPost(urls[0]);
try {
ArrayList<NameValuePair> paresNomeValor = new ArrayList<NameValuePair>();
Iterator<String> iterator = parametros.keySet().iterator();
while (iterator.hasNext()) {
String chave = iterator.next();
paresNomeValor.add(new BasicNameValuePair(chave, parametros.get(chave)));
}
post.setEntity(new UrlEncodedFormEntity(paresNomeValor, "UTF-8"));
HttpResponse respostaRequisicao = clienteHttp.execute(post);
StatusLine statusRequisicao = respostaRequisicao.getStatusLine();
if (statusRequisicao.getStatusCode() == HttpURLConnection.HTTP_OK) {
resultado = EntityUtils.toByteArray(respostaRequisicao.getEntity());
resposta = new String(resultado, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
} catch (Exception e) {
}
return resposta;
}
@Override
protected void onPostExecute(String param) {
dialogo.dismiss();
}
}
}
嘗試在按鈕偵聽器中注釋掉resposta.get()
調用。 我猜它只是阻塞了主UI線程,直到任務完成。
幾件事。 首先,不要為ASyncClass創建實例,因為根據android文檔,您只能調用一次。 這樣執行: new Requisicao().execute(webAddress + "/login");
另外,不要調用requisicao.get()
,這將再次根據文檔“等待以完成計算,然后檢索其結果”(也稱為阻塞),從您的異步類中添加重寫:
protected void onProgressUpdate(Long... progress) {
CallBack(progress[0]); // for example
}
其中CallBack是UI線程中的一個函數,它將長時間處理進程,字符串,或其他任何您想回退的進程。 提醒您,您的ASync類將必須在UI類中定義,而不是單獨定義。
移動你的
private ProgressDialog dialogo = null;
就像使用HTTPClient一樣進入AsyncTask的字段,因為您似乎沒有在任何地方使用它並嘗試在構造函數中創建對話框
public Requisicao(HashMap<String, String> params) {
parametros = params;
dialogo = new ProgressDialog(MyApp.this);
}
在postExecute中
if (dialogo .isShowing()) {
dialogo .dismiss();
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.