我的应用程序中有两个活动.在我的活动A中,我使用一个AsyncTask,第二个活动B也使用另一个AsyncTask.在我的活动A中,我将一些数据上传到服务器,在我的活动B中,我正在尝试从服务器下载一些其他数据.这两个都在AsyncTask中运行.我的问题是当我尝试从Activity中下载数据时,onPreExecute()调用了Activity B 方法,但是doInBackground()没有调用方法,它正在等待第一个Activity A的doInBackground()操作完成.为什么会这样?是否可以同时运行多个后台操作..
在活动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
}
}
Run Code Online (Sandbox Code Playgroud)
在我的活动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
}
}
Run Code Online (Sandbox Code Playgroud)
Aru*_*n C 25
使用执行程序如下
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new Save_data().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, location);
} else {
new Save_data().execute(location);
}
Run Code Online (Sandbox Code Playgroud)
看到这个
Mar*_*ski 16
是的,确实如此,但自从Honeycomb以来,AsyncTaskAndroid的处理方式发生了变化.从HC +开始,它们按顺序执行,而不是像过去那样并行执行.解决方案是像这样调用它们(将它放在单独的工具类中):
public class AsyncTaskTools {
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task) {
execute(task, (P[]) null);
}
@SuppressLint("NewApi")
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task, P... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地打电话:
AsyncTaskTools.execute( new MyAsyncTask() );
Run Code Online (Sandbox Code Playgroud)
或者使用params(但我更喜欢通过任务构造函数建议passign params):
AsyncTaskTools.execute( new MyAsyncTask(), <your params here> );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19677 次 |
| 最近记录: |