现在的位置: 首页 > 综合 > 正文

Android之AsyncTask面试

2014年03月31日 ⁄ 综合 ⁄ 共 4283字 ⁄ 字号 评论关闭

AsyncTask的执行分为四个步骤
onPreExecute():当任务执行之前开始调用此方法,可以在这里显示进度对话框
doInBackground(Params...)此方法在后台线程执行,完成任务的主要工作,通常需要较长
的时间。执行过程中可以调用public Progress(Progress...)来更新任务的进度
onProgressUpdate(Progress...)此方法在主线程执行,用于显示任务执行的进度。
onPostExecute(Result)此方法在主线程执行,任务执行的结果作为此方法的参数返回
AsyncTask的三个泛型参数说明(三个参数可以是任何类型)

第一个参数:传入doInBackground()方法的参数类型
第二个参数:传入onProgressUpdate()方法的参数类型
第三个参数:传入onPostExecute()方法的参数类型,也是doInBackground()方法的返回类型

使用AsyncTask类,遵守的准则:1,  Task的实例必须在UI thread中创建;2,  Execute方法必须在UI thread中调用3,  不要手动的调用onPfreexecute(),onPostExecute(result)Doinbackground(params…),onProgressupdate(progress…)这几个方法;4,  该task只能被执行一次,否则多次调用时将会出现异常;
AsyncTask的整个调用过程都是从execute方法开始的,一旦在主线程中调用execute方法,就可以通过onpreExecute方法,这是一个预处理方法,比如可以在这里开始一个进度框,同样也可以通过onprogressupdate方法给用户一个进度条的显示,增加用户体验;最后通过onpostexecute方法,相当于handler处理UI的方式,在这里可以使用在doinbackground得到的结果处理操作UI。此方法在主线程执行,任务执行的结果作为此方法的参数返回

    <uses-permission android:name="android.permission.INTERNET"/>

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    
    <EditText android:id="@+id/urls"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint"
        />
    <Button 
        android:id="@+id/load"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/load"/>

    <TextView
        android:id="@+id/txt_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

 

package com.android.xiong.aysnctasktest;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

	Button load;
	EditText url;
	TextView showMessage;
	HttpClient httpClient = new DefaultHttpClient();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		load = (Button) findViewById(R.id.load);
		url = (EditText) findViewById(R.id.urls);
		showMessage = (TextView) findViewById(R.id.txt_message);
		load.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				PageTask pageTask = new PageTask();
				String urls = url.getText().toString().trim();
				if (!urls.equals("")) {
					pageTask.execute("http://"+urls);
				}
			}
		});
	}

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

	// 第一个参数表示传入 doInBackground参数类型
	// 第二个参数表示传入onProgressUpdate参数类型
	// 第三个参数表示传入onPostExecute参数类型
	class PageTask extends AsyncTask<Object, Object, Object> {

		ProgressDialog dialog;

		// 执行任务之前调用该方法
		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setTitle("请稍等");
			dialog.setMessage("网页正在加载中。。。");
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
							//取消任务
							PageTask.this.cancel(true);
						}
					});
			dialog.show();
		}

		// 操作耗时任务
		@Override
		protected Object doInBackground(Object... params) {
			HttpGet get = new HttpGet(params[0].toString());
			// 发送get请求
			try {
				HttpResponse response = httpClient.execute(get);
				if (response.getStatusLine().getStatusCode() == 200) {
					// 获取响应的字符串
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						return EntityUtils.toString(entity);
					}
				}
			} catch (ClientProtocolException e) {
				new RuntimeException(e);
			} catch (IOException e) {
				new RuntimeException(e);
			}
			return null;
		}

		// 显示任务的进度
		@Override
		protected void onProgressUpdate(Object... values) {
			super.onProgressUpdate(values);
		}

		// 任务执行的结果作为此方法的返回参数result其实是doInBackgSround(Object... params)的返回值
		@Override
		protected void onPostExecute(Object result) {
			showMessage.setText(result.toString());
			dialog.dismiss();
		}

	}

}

 

抱歉!评论已关闭.