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;  
    
    @Override
    protected 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;
			}
		}
	};

    @Override
    public 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> {  
  
    private TextView textView;  
    private ProgressBar progressBar;  
      
    private static Gson gson = new GsonBuilder().setVersion(1).create();
	List listnames = new ArrayList();
	List listid = new ArrayList();
	
    public ProgressBarAsyncTask(TextView textView, ProgressBar progressBar) {  
        super();  
        this.textView = textView;  
        this.progressBar = progressBar;  
    }  
  
  
    /**  
     * 这里的String参数对应AsyncTask中的第一个参数   
     * 这里的List返回值对应AsyncTask的第三个参数  
     * 该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改  
     * 但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作  
     */
    @Override
	protected List doInBackground(String... params) {
		// TODO Auto-generated method stub
		List areaList = null;
		HttpEntity entity;
		try {
			entity = HttpUtil.send(HttpUtil.METHOD_GET, params[0], null);
			String json=EntityUtils.toString(entity);
			Type type = new TypeToken>() {}.getType();
			areaList = gson.fromJson(json, type);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return areaList;
	}
  
  
    /**  
     * 这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值)  
     * 在doInBackground方法执行结束之后在运行,并且运行在UI线程当中 可以对UI空间进行设置  
     */  
    @Override
	protected void onPostExecute(List result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		textView.setText("异步操作执行结束" + result);
		if(result == null)
		{
			Log.e("", "result == null");
		}
		else
		{
			Log.e("", "result != null"+result.size());
			for(int i = 0;i


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 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}]


你可能感兴趣的:(Android,AsyncTask,onPostExecute)