小结android中的AsyncTask

anroid中有两种异步加载数据然后更新UI的方式,分别是handler和AsyncTask。

asynctask有三个参数

<span style="font-size:14px;">AsyncTask<Params, Progress, Result></span>
params:是启动任务执行时传过来的参数,一般是任务处理的url

progress:是任务处理后的进度

result:是任务处理后返回的结果

一个异步任务的执行一般包括以下几个步骤:

1.execute(Params... params),执行一个异步任务时,在代码中调用此方法,触发异步任务的执行。

2.onPreExecute(),在execute(Params... params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。例如:“正在加载”的提示框。

3.doInBackground(Params... params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,此方法将接收输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。

4.onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上。

5.onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。


Asynctask.java

public class AysncTaskList extends AsyncTask<String, Integer, JSONArray> {

	private static final String TAG = "TAG";
	private CallbackInterface callbackInterface;
	private List<WeiboModel> list;
	private UserInfo userInfo;

	public AysncTaskList(Context mcContext, CallbackInterface callbackInterface) {
		super();
		this.callbackInterface = callbackInterface;

	}

	@Override
	protected JSONArray doInBackground(String... arg0) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(
				"http://59.46.175.165:8080/yicheng_mobile/mobileJson");
		try {
			// 获取我的空间的所有的我的动态列表(首页的)(TA的空间首页动态列表)
			Map<String, String> mParam = new HashMap<String, String>();
			mParam.put("user_uuid", "");
			mParam.put("version", "4.5");
			mParam.put("method", "space.getSpaceBlogList");
			mParam.put("uid", "1000002");
			mParam.put("ta_uid", "1000002");
			mParam.put("start_row", "1");
			mParam.put("rows_per_page", "10");

			JSONObject objBlogList = new JSONObject(mParam);
			StringEntity entityBlogList = new StringEntity(
					objBlogList.toString());
			post.setEntity(entityBlogList);
			HttpResponse responseSpaceBlogList = client.execute(post);// 请求
			Log.i(TAG, "resCode = "
					+ responseSpaceBlogList.getStatusLine().getStatusCode()); // 获取响应码

			HttpEntity httpEntitySpaceBlogList = responseSpaceBlogList
					.getEntity();// 接收服务器数据
			String strResponseSpaceBlogList = EntityUtils
					.toString(httpEntitySpaceBlogList);// 把返回的数据转换成String

			// 获取我的空间的所有的我的动态列表(首页的)(TA的空间首页动态列表)
			if (httpEntitySpaceBlogList != null) {
				try {
					list = new ArrayList<WeiboModel>();
					Gson gson = new Gson();
					JSONArray jsonArray = new JSONArray(
							strResponseSpaceBlogList);
					for (int i = 0; i < jsonArray.length(); i++) {
						WeiboModel model = null;
						JSONObject everyJsonObject = jsonArray.optJSONObject(i);
						if (everyJsonObject != null) {
							model = gson.fromJson(everyJsonObject.toString(),
									WeiboModel.class);
							list.add(model);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			// 我的空间基本信息(头部信息)
			Map<String, String> getSpaceMyInfo = new HashMap<String, String>();
			getSpaceMyInfo.put("start_row", "1");
			getSpaceMyInfo.put("rows_per_page", "10");
			getSpaceMyInfo.put("user_uuid", "");
			getSpaceMyInfo.put("version", "4.5");
			getSpaceMyInfo.put("method", "space.getSpaceMyInfo");
			getSpaceMyInfo.put("uid", "1000002");

			JSONObject objSpaceMyInfo = new JSONObject(getSpaceMyInfo);
			StringEntity entitySpaceMyInfo = new StringEntity(
					objSpaceMyInfo.toString());
			post.setEntity(entitySpaceMyInfo);

			HttpResponse responseSpaceMyInfo = client.execute(post);
			Log.i(TAG, "resCode = "
					+ responseSpaceMyInfo.getStatusLine().getStatusCode()); 

			HttpEntity httpEntity = responseSpaceMyInfo.getEntity();
			String str = EntityUtils.toString(httpEntity);

			if (httpEntity != null) {
				JSONObject obj;
				try {
					Gson gson = new Gson();
					obj = new JSONArray(str).optJSONObject(0);
					if (obj != null) {
						userInfo = gson
								.fromJson(obj.toString(), UserInfo.class);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPreExecute() {

		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(JSONArray result) {
		callbackInterface.operation(list, userInfo);
		
		super.onPostExecute(result);
	}

}

主线程对asynctask的操作:

public class MainActivity extends BaseActivity {

	ListView myListView = null;
	LinearLayout headLinLinearLayout;
	LinearLayout statusLinearLayout;
	LinearLayout fansLinearLayout;
	LinearLayout focusLinearLayout;
	LinearLayout myMessageLinearLayout;
	LinearLayout myCardLinearLayout;
	LinearLayout myCollectionLinearLayout;

	ListViewAdapter adapter = null;
	private static final String TAG = "1111111111111111";
	private AysncTaskList aysncTaskList;
	private ImageView userHeadImg;
	private TextView blogListUserName;
	private TextView userName;
	private TextView userCountPa;
	private TextView userCountGold;
	private TextView userSign;
	private TextView userTrends;
	private TextView userFansCounts;
	private TextView userAttentionCount;
	private ImageButton imgSoulMassage;
	private ImageButton imgDailyMission;
	private DisplayImageOptions options;
	protected ImageLoader imageLoader = ImageLoader.getInstance();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_main);
		super.onCreate(savedInstanceState);

	}

	@Override
	public void initViewAfterOnCreate() {
		// 首页的布局
		myListView = (ListView) findViewById(R.id.listview);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.activity_main_headerview, null);
		adapter = new ListViewAdapter(this, imageLoader);
		myListView.addHeaderView(view);
		myListView.setAdapter(adapter);

		// 头部信息
		userHeadImg = (ImageView) findViewById(R.id.img_user_headpic);
		userName = (TextView) findViewById(R.id.tv_user_name);
		userCountPa = (TextView) findViewById(R.id.tv_user_count_pa);
		userCountGold = (TextView) findViewById(R.id.tv_user_count_gold);
		userSign = (TextView) findViewById(R.id.tv_user_sign);
		userTrends = (TextView) findViewById(R.id.tv_trends);// 动态数量
		userFansCounts = (TextView) findViewById(R.id.tv_fans);// 粉丝数量
		userAttentionCount = (TextView) findViewById(R.id.tv_focus);// 关注数量

		// 首页信息
		blogListUserName = (TextView) findViewById(R.id.user_name);

	}

	@Override
	public void initDataAfterOnCreate() {

		this.options = getOptions();
		// 开启线程
		aysncTaskList = new AysncTaskList(this, callbackInterface);
		aysncTaskList.execute();
	}

	private CallbackInterface callbackInterface = new CallbackInterface() {

		@Override
		public void operation(List<WeiboModel> list, UserInfo info) {
			userName.setText(info.username);
			userFansCounts.setText(info.fans_count + "");
			userSign.setText(info.user_sign);

			String headurl = "http://59.46.175.165/bbs/uc_server/avatar.php?uid=";
			String str = "&size=middle";
			imageLoader.displayImage(headurl + info.uid, userHeadImg, options);

			adapter.refreshData(list, info);
		}
	};

	private DisplayImageOptions getOptions() {
		DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY)
				.resetViewBeforeLoading(true).build();
		return options;
	}

}

CallbackInterface接口:

public interface CallbackInterface {

	void operation(List<WeiboModel> list,UserInfo info);
}


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值