我在我的应用程序的两项活动。在我的活动。我很使用一个AsyncTask的第二b活动还使用另外一个AsyncTask的。在我的活动一个我已经有些数据上传到服务器,并在我的b活动我试图从服务器上。无论这些在AsyncTask的运行下载一些其他的数据。我的问题是,当我试图从服务器的活动B下载数据preExecute()方法被调用,但doInBackground()方法并没有把它叫做等待到第一个活动A的doInBackground()操作已结束。它为什么发生?是否有可能在同一时间运行多个后台操作。
在活动A
的ImageButton submit_button =(的ImageButton)findViewById(R.id.submit_button);
submit_button.setOnClickListener(新OnClickListener()
{
公共无效的onClick(查看record_button)
{
新Save_data()执行()。
}
});
类Save_data扩展的AsyncTask<字符串,整数,整数GT;
{
在preExecute保护无效()
{
}
保护整数doInBackground(字符串...为arg0)
{
//此处上传数据
}
}
在我b活动
的ImageButton get_button =(的ImageButton)findViewById(R.id.get_button);
get_button.setOnClickListener(新OnClickListener()
{
公共无效的onClick(查看record_button)
{
新download_process()执行()。
}
});
类download_process扩展的AsyncTask<字符串,整数,整数GT;
{
在preExecute保护无效()
{
Log.e(pre-执行,被称为); //这个日志效果很好
}
保护整数doInBackground(字符串...为arg0)
{
//下载数据在这里
}
}
解决方案
使用执行人如下:
如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.HONEYCOMB){
新Save_data()executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,位置);
} 其他 {
新Save_data()执行(位置);
}
请参阅这
I've two activities in my application. In my Activity A i'm using one AsyncTask and second Activity B also using another one AsyncTask . In my Activity A i've upload some data to server and in my Activity B I'm trying to download some other data from server .Both these are running in AsyncTask. My problem is when i trying to download data from server in Activity B onPreExecute() method was called but doInBackground() method was not called it is waiting up to the first Activity A's doInBackground() action finished . Why it is happened ? Is it possible to run more than one background actions at a same time ..
In Activity A
ImageButton submit_button = (ImageButton) findViewById(R.id.submit_button);
submit_button.setOnClickListener(new OnClickListener()
{
public void onClick(View record_button)
{
new Save_data().execute();
}
});
class Save_data extends AsyncTask<String, Integer, Integer>
{
protected void onPreExecute()
{
}
protected Integer doInBackground(String... arg0)
{
//uploading data here
}
}
In my Activity B
ImageButton get_button = (ImageButton) findViewById(R.id.get_button);
get_button.setOnClickListener(new OnClickListener()
{
public void onClick(View record_button)
{
new download_process().execute();
}
});
class download_process extends AsyncTask<String, integer, integer>
{
protected void onPreExecute()
{
Log.e("pre-execute","has been called");//This Log works well
}
protected Integer doInBackground(String... arg0)
{
//downloading data here
}
}
解决方案
use executor as follows
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new Save_data().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, location);
} else {
new Save_data().execute(location);
}
See this