2010-07-21 13 views
5

La documentazione di Android indica che AsyncTask postExecute() viene chiamato nel thread dell'interfaccia utente. Avevo l'impressione che postExecute() fosse chiamato dal Thread in cui è stato chiamato execute(): Ho utilizzato un AsyncTask in un servizio in background con il suo thread e nel thread del servizio è stato chiamato postExecute(), non il thread principale.
Tuttavia, di recente ho avuto un problema con il postExecute() non è stato chiamato affatto, mentre è stata generata un'eccezione: "invio di un messaggio a un gestore su un thread morto".Android: può AsyncTask restituire in un altro thread rispetto al thread UI?

Come è esattamente:
- AsyncTask deve essere utilizzato SOLO dal thread principale?
- in caso contrario, in quale thread si deve chiamare postExecute(): sempre il thread dell'interfaccia utente o il thread di chiamata execute()?

Grazie

+0

La documentazione * appare * anche fuorviante, mentre non ho attraversato il thread l'eccezione che stai ottenendo è stata la mia esperienza che quando si utilizza un 'AsyncTask' al di fuori dell'interfaccia utente' onPostExecute' si verifica dal thread chiamante e non necessariamente dal thread UI (quindi richiede un 'Handler' se l'interfaccia utente deve essere manipolata). –

risposta

14

I metodi pre e postExecute di AsyncTask vengono richiamati sul thread su cui è stata creata l'istanza dell'attività. Dove si chiama execute() non importa. Il thread su cui si crea l'attività deve essere un thread looper e in pratica dovrebbe essere sempre il thread principale (o thread dell'interfaccia utente).

+0

Grazie per la risposta concreta! –

+1

E 'ancora il caso in 4.1+? Ho avviato un'attività asincrona all'interno del thread del gestore ma il risultato è ancora sul thread principale. – Teodor

+0

Che dire se hai un listener creato su un thread diverso? se lo chiami, si innescherà anche sul thread che è stato creato? – JY2k

2

Sembra che si può iniziare AsyncTask da qualche altra parte che il thread principale, ma il postExecute è realmente eseguito sul thread principale. Qui è la mia prova, ditemi se vi sembra logico per voi:

public class AsyncLoader extends AsyncTask<Context, String, Boolean> { 
private ConnectivityManager cm; 
private ArrayList<Contact> nameList; 
private Context ctx; 
private static int i = 0; 

@Override 
protected Boolean doInBackground(Context... params) { 
    ctx = params[0]; 
    cm = (ConnectivityManager) params[0].getSystemService(Activity.CONNECTIVITY_SERVICE); 
    if (i < 3) { 
     i++; 
     new AsyncLoader().execute(ctx); 
     System.out.println("Thread name (from doInBackground) : " + Thread.currentThread().getName()); 
     System.out.println("compteur async " + i); 
    } 
    if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable()) { 
     nameList = (ArrayList<Contact>) ContactLoaderXml.loadContactsData(); //this is a loading from the web + sax parser 
     return true; 
    } else { 
     return false; 
    } 
} 
@Override 
protected void onPostExecute(Boolean result) { 
    super.onPostExecute(result); 
    System.out.println("Thread name (from postexecute) : " + Thread.currentThread().getName()); 
} 
} 

Ecco la stacktrace dopo i compiti:

I/System.out( 641): Thread name (from doInBackground) : AsyncTask #1 
I/System.out( 641): compteur async 1 
I/System.out( 641): Thread name (from doInBackground) : AsyncTask #2 
I/System.out( 641): compteur async 2 
I/System.out( 641): Thread name (from doInBackground) : AsyncTask #3 
I/System.out( 641): compteur async 3 
I/System.out( 641): Thread name (from postexecute) : main 
I/System.out( 641): Thread name (from postexecute) : main 
I/System.out( 641): Thread name (from postexecute) : main 
I/System.out( 641): Thread name (from postexecute) : main 

Non so il motivo per cui il palo eseguire è fatto 4 volte comunque ...

+0

Immagino perché hai chiamato execute sul tuo oggetto per entrare nel primo doInBackground, quindi onPostexecute è chiamato 4 volte. Non sono sicuro che la creazione del compito nel doInBackground sia una buona idea ... – user244129

Problemi correlati