Eu estava lendo sobre AsyncTask
, e tentei o programa simples abaixo. Mas parece que não funciona. Como posso fazer com que funcione?
public class AsyncTaskActivity extends Activity {
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
public void onClick(View view){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
return null;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
Estou apenas a tentar mudar a etiqueta após 5 segundos no processo de fundo.
Este é o meu **main.xml***:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="10dip">
</ProgressBar>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Progress" >
</Button>
<TextView android:id="@+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replace"/>
</LinearLayout>
Ok, você está tentando acessar o GUI através de outro tópico. Isto, no essencial, não é uma boa prática.
A AsyncTask executa tudo em doInBackground()
dentro de outro thread, que não tem acesso à GUI onde estão suas views.
PreExecute()preExecute()
e postExecute()
oferecem-lhe acesso à GUI antes e depois do levantamento pesado ocorrer nesta nova thread, você pode até mesmo passar o resultado da longa operação para postExecute()
para então mostrar qualquer resultado do processamento.
Veja estas linhas onde você está atualizando seu TextView mais tarde:
TextView txt = findViewById(R.id.output);
txt.setText("Executed");
coloque-os em onPostExecute()
Você verá seu texto TextView atualizado após a conclusão do doInBackground
.
EDIT: Notei que o seu onClick ouvinte não verifica para ver qual Vista foi seleccionada. Acho que a maneira mais fácil de fazer isso é através de declarações de mudança. Eu tenho uma classe completa editada abaixo com todas as sugestões para evitar confusões.
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class AsyncTaskActivity extends Activity implements OnClickListener {
Button btn;
AsyncTask<?, ?, ?> runningTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = findViewById(R.id.button1);
// because we implement OnClickListener we only have to pass "this"
// (much easier)
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
if (runningTask != null) runningTask.cancel(true);
runningTask = new LongOperation();
runningTask.execute();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// cancel running task(s) to avoid memory leaks
if (runningTask != null) runningTask.cancel(true);
}
private final class LongOperation extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// we were cancelled, stop sleeping!
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
}
}
I'tenho certeza que está executando corretamente, mas você'está tentando mudar os elementos da UI na linha de fundo e isso ganhou't fazer.
Revise a sua chamada e a AsyncTask da seguinte forma:
**Aula de chamada***
Note: Eu pessoalmente sugiro utilizar onPostExecute()
onde quer que você execute seu thread AsyncTask e não na classe que estende a AsyncTask em si. Eu acho que isso torna o código mais fácil de ler especialmente se você precisar da AsyncTask em vários lugares manipulando os resultados um pouco diferentes.
new LongThread() {
@Override public void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}.execute("");
LongThread class (estende AsyncTask):
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Executed";
}
Mova estas duas linhas:
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");
do seu método AsyncTask's doInBackground
e coloque-os no método onPostExecute
. O seu AsyncTask
deve ser parecido com isto:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
Thread.sleep(5000); // no need for a loop
} catch (InterruptedException e) {
Log.e("LongOperation", "Interrupted", e);
return "Interrupted";
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}