AsyncTask onPostExecute 未执行问题

2024-06-01 15:38

本文主要是介绍AsyncTask onPostExecute 未执行问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在android4.0以下设备上onPostExecute不执行,doInBackground也无抛出异常。

在android4.2以上设备上onPostExecute是执行的,没问题。

那么问题就来了,一路查寻,牵扯出好多问题。

以下是我个人遇到的情况,新建个测试AsyncTask项目没有问题,但是在原项目下问题就来了。

AndroidManifest.xml里加入了android:launchMode="singleTask"

得在UI线程里调用execute;在onCreate中调用,onPostExecute是不执行的。


android-support-v4.jar低版本下,在FragmentActivity下调用,onPostExecute是不执行的。


关键在MAINActivity onCreate中添加

try {

Class.forName("android.os.AsyncTask");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}


以下是案例,有关HTTP请求,需要加入gson.jar

package com.example.asynctasktest;import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.view.View.OnClickListener;public class MainActivity extends Activity {private Button button;  private ProgressBar progressBar;  private TextView textView;  @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button)findViewById(R.id.button03);  progressBar = (ProgressBar)findViewById(R.id.progressBar02);  textView = (TextView)findViewById(R.id.textView01);  button.setOnClickListener(new OnClickListener() {  @Override  public void onClick(View v) {  startGetArea();}  });  ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView, progressBar);  asyncTask.execute("http://www.xxx.com/getAreaList.htm");}public void startGetArea(){Message msg = mhandler.obtainMessage();msg.what = 1;mhandler.sendMessage(msg);}/*** handler处理消息机制*/protected Handler mhandler = new Handler() {public void handleMessage(Message message) {switch (message.what) {case 1:new ProgressBarAsyncTask(textView, progressBar).execute("http://www.xxx.com/getAreaList.htm");break;}}};@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}


package com.example.asynctasktest;import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;import android.os.AsyncTask;  
import android.util.Log;
import android.widget.ProgressBar;  
import android.widget.TextView;import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;/**  * 生成该类的对象,并调用execute方法之后  * 首先执行的是onProExecute方法  * 其次执行doInBackgroup方法  *  */  
public class ProgressBarAsyncTask extends AsyncTask<String, Integer, List<AllArea>> {  private TextView textView;  private ProgressBar progressBar;  private static Gson gson = new GsonBuilder().setVersion(1).create();List<String> listnames = new ArrayList<String>();List<String> listid = new ArrayList<String>();public ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) {  super();  this.textView = textView;  this.progressBar = progressBar;  }  /**  * 这里的String参数对应AsyncTask中的第一个参数   * 这里的List<AllArea>返回值对应AsyncTask的第三个参数  * 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改  * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作  */@Overrideprotected List<AllArea> doInBackground(String... params) {// TODO Auto-generated method stubList<AllArea> areaList = null;HttpEntity entity;try {entity = HttpUtil.send(HttpUtil.METHOD_GET, params[0], null);String json=EntityUtils.toString(entity);Type type = new TypeToken<List<AllArea>>() {}.getType();areaList = gson.fromJson(json, type);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return areaList;}/**  * 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)  * 在doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI空间进行设置  */  @Overrideprotected void onPostExecute(List<AllArea> result) {// TODO Auto-generated method stubsuper.onPostExecute(result);textView.setText("异步操作执行结束" + result);if(result == null){Log.e("", "result == null");}else{Log.e("", "result != null"+result.size());for(int i = 0;i<result.size();i++){listnames.add(result.get(i).getIndustryName());listid.add(result.get(i).getId()+"");}}}/*** 该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置 */@Override  protected void onPreExecute() {  textView.setText("开始执行异步线程");  }  /**  * 这里的Intege参数对应AsyncTask中的第二个参数  * 在doInBackground方法当中,,每次调用publishProgress方法都会触发onProgressUpdate执行  * onProgressUpdate是在UI线程中执行,所有可以对UI空间进行操作  */  @Override  protected void onProgressUpdate(Integer... values) {  int vlaue = values[0];  progressBar.setProgress(vlaue);  } 
}  


package com.example.asynctasktest;import java.util.ArrayList;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;import android.util.Log;/***	HTTP请求方式类* @author Administrator**/
public class HttpUtil {public static final int METHOD_GET=0;public static final int METHOD_POST=1;/*** * @param method GET请求* @param url 请求路径* @param pairs 提交参数* @return* @throws Exception*/public static HttpEntity send(int method,String url,ArrayList<NameValuePair> pairs)throws Exception{HttpClient client=new DefaultHttpClient();HttpResponse resp=null;switch(method){case METHOD_GET:Log.i("send", url);HttpGet get=new HttpGet(url);resp=client.execute(get);Log.i("send", resp.toString());break;case METHOD_POST:HttpPost post=new HttpPost(url);HttpEntity entity=new UrlEncodedFormEntity(pairs,"utf-8");post.setEntity(entity);post.setHeader("Content-Type", "x-www-form-urlencoded");resp=client.execute(post);break;}return resp.getEntity();}
}

package com.example.asynctasktest;import java.io.Serializable;public class AllArea implements Serializable{/*** */private static final long serialVersionUID = -8325422695071123262L;private int id;private int type;private int parentId;private String areaName;private String areaNo;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getType() {return type;}public void setType(int type) {this.type = type;}public int getParentId() {return parentId;}public void setParentId(int parentId) {this.parentId = parentId;}public String getIndustryName() {return areaName;}public void setIndustryName(String industryName) {this.areaName = industryName;}public String getIndustryDesc() {return areaNo;}public void setIndustryDesc(String industryDesc) {this.areaNo = industryDesc;}}

[{"state":1,"type":1,"seq":1,"parentId":1,"areaNo":"3601","areaName”:”东城区”,”id”:11},{“state":1,"type":1,"seq":2,"parentId":1,"areaNo":"3602","areaName”:”西城区”,”id”:22},{“state":1,"type":1,"seq":3,"parentId":1,"areaNo":"3603","areaName”:”海淀区”,”id”:33},{“state":1,"type":1,"seq":4,"parentId":1,"areaNo":"3604","areaName”:”朝阳区”,”id”:44},{“state":1,"type":1,"seq":5,"parentId":1,"areaNo":"3605","areaName”:”昌平区”,”id”:55},{“state":1,"type":1,"seq":6,"parentId":1,"areaNo":"3606","areaName”:”丰台区”,”id”:66}]


这篇关于AsyncTask onPostExecute 未执行问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1021410

相关文章

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

mybatis和mybatis-plus设置值为null不起作用问题及解决

《mybatis和mybatis-plus设置值为null不起作用问题及解决》Mybatis-Plus的FieldStrategy主要用于控制新增、更新和查询时对空值的处理策略,通过配置不同的策略类型... 目录MyBATis-plusFieldStrategy作用FieldStrategy类型每种策略的作

linux下多个硬盘划分到同一挂载点问题

《linux下多个硬盘划分到同一挂载点问题》在Linux系统中,将多个硬盘划分到同一挂载点需要通过逻辑卷管理(LVM)来实现,首先,需要将物理存储设备(如硬盘分区)创建为物理卷,然后,将这些物理卷组成... 目录linux下多个硬盘划分到同一挂载点需要明确的几个概念硬盘插上默认的是非lvm总结Linux下多

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

pip install jupyterlab失败的原因问题及探索

《pipinstalljupyterlab失败的原因问题及探索》在学习Yolo模型时,尝试安装JupyterLab但遇到错误,错误提示缺少Rust和Cargo编译环境,因为pywinpty包需要它... 目录背景问题解决方案总结背景最近在学习Yolo模型,然后其中要下载jupyter(有点LSVmu像一个

解决jupyterLab打开后出现Config option `template_path`not recognized by `ExporterCollapsibleHeadings`问题

《解决jupyterLab打开后出现Configoption`template_path`notrecognizedby`ExporterCollapsibleHeadings`问题》在Ju... 目录jupyterLab打开后出现“templandroidate_path”相关问题这是 tensorflo

如何解决Pycharm编辑内容时有光标的问题

《如何解决Pycharm编辑内容时有光标的问题》文章介绍了如何在PyCharm中配置VimEmulator插件,包括检查插件是否已安装、下载插件以及安装IdeaVim插件的步骤... 目录Pycharm编辑内容时有光标1.如果Vim Emulator前面有对勾2.www.chinasem.cn如果tools工

在MySQL执行UPDATE语句时遇到的错误1175的解决方案

《在MySQL执行UPDATE语句时遇到的错误1175的解决方案》MySQL安全更新模式(SafeUpdateMode)限制了UPDATE和DELETE操作,要求使用WHERE子句时必须基于主键或索引... mysql 中遇到的 Error Code: 1175 是由于启用了 安全更新模式(Safe Upd

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH