我試圖運行它們兩個AsyncTask序列並且不起作用,它只運行第一個。如果我更改AsyncTask的順序,因爲只運行第一個,第二個不是,那麼運行TimerTask。看看我的代碼: (請原諒我的語言,我會說西班牙語。)如何連續運行AsyncTask?
public class ServicioPrincipal extends Service
{ ...
public int onStartCommand(Intent intent, int flags, int startId)
{
new ServerAsyncTask().execute(serverSocket, getApplicationContext());
new ClientEspejoAsyncTask().execute(getApplicationContext());
timerTask = new TimerTask()
{
@Override
public void run()
{
//Log.i(TAG, "Ejecutando la tarea del servicio");
Utilitario.escribirLog("ServicioPrincipal: iniciarServicioPrincipal: timer is running...");
}
};
try
{
timer.scheduleAtFixedRate(timerTask, 0, 30000); //, 0, 15000);
}
catch(Exception ex)
{
Utilitario.escribirLog("ServicioPrincipal: iniciarServicioPrincipal: catch:"+ex.getMessage());
}
}
...
}
我的課:
private class ServerAsyncTask extends AsyncTask<Object, Void, String>
{
@Override
protected String doInBackground(Object... objs)
{
try
{
Utilitario.escribirLog("ServicioPrincipal: ServerAsyncTask: doInBackground");
server = new Server((ServerSocket)objs[0], (Context)objs[1]);
server.iniciarServer();
return "1";
}
catch (Exception e)
{
Utilitario.escribirLog("ServicioPrincipal: ServerAsyncTask: doInBackground: catch:"+e.getMessage());
return "0";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result)
{
Utilitario.escribirLog("ServicioPrincipal: ServerAsyncTask: onPostExecute-"+result);
pararServicioPrinipal();
}
}
private class ClientEspejoAsyncTask extends AsyncTask<Object, Void, String>
{
@Override
protected String doInBackground(Object... objs)
{
// params comes from the execute() call: params[0] is the url.
try
{
Utilitario.escribirLog("ServicioPrincipal: ClientEspejoAsyncTask: doInBackground");
clientEspejo = new ClientEspejo((Context)objs[0]);
clientEspejo.iniciarClientEspejo();
return "1";
}
catch (Exception e)
{
Utilitario.escribirLog("ServicioPrincipal: ClientEspejoAsyncTask: doInBackground: catch:"+e.getMessage());
return "0";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result)
{
Utilitario.escribirLog("ServicioPrincipal: ClientEspejoAsyncTask: onPostExecute-"+result);
pararServicioPrinipal();
}
}
非常感謝你提前。
這是一個好主意,但不適用於這種情況,因爲我的第一個AsyncTask OnPostExecute只在doInBackground完成運行時運行,我需要同時運行AsyncTask。 對不起,我說西班牙語。 – Heberth
不用擔心語言^^,關於同時運行多個AsyncTask,你可以查看這篇文章http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same-time-not-可能 – reidzeibel
非常感謝,我服務我的我可以muxo和解決問題。 – Heberth