我正在尝试运行它们两个AsyncTask序列并且不起作用,它只运行第一个。如果我更改AsyncTask的顺序,因为只运行第一个,第二个不运行,然后运行TimerTask。看看我的代码: (请原谅我的语言,我会说西班牙语。)
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();
}
}
非常感谢你。
答案 0 :(得分:2)
将第二个AsyncTask放在First AsyncTask的onPostExecute
内:
AsyncTask1 onPostExecute {
new AsyncTask2().execute();
}
应该这样做,祝你好运^^
答案 1 :(得分:1)
我在AsyncTask
中没有这样做,但您可以尝试在第一项任务的doInBackground{}
内执行第二项任务。
@Override
protected String doInBackground(Object... objs)
{
.
.
.
new ClientEspejoAsyncTask().execute(objs[0]);
}
但我会建议你使用Thread代替这种概念。 http://www.tutorialspoint.com/java/java_thread_synchronization.htm