android 线程之AsyncTask

AsyncTask是抽象类,子类必须实现抽象方法doInBackground(Params... p) ,在此方法中实现任务的执行工作,比如连接网络获取数据等。

AsyncTask 的执行分为四个步骤,与前面定义的TaskListener类似。每一步都对应一个回调方法,需要注意的是这些方法不应该由应用程序调用,开发者需要做的就是实现这些方法。在任务的执行过程中,这些方法被自动调用。

    * onPreExecute() 当任务执行之前开始调用此方法,可以在这里显示进度对话框。
    * doInBackground(Params...) 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。
    * onProgressUpdate(Progress...) 此方法在主线程执行,用于显示任务执行的进度。
    * onPostExecute(Result) 此方法在主线程执行,任务执行的结果作为此方法的参数返回。

使用方法:

1.在主线程中调用task.execute(is);方法。参数个数是可变的,可以传0个,1个,2个或者更多,当调用这个函数系统就会自动去调用doInBackgound()函数。

2.extends AsyncTask<X, Y, Z>参数类型,其中X为doInBackground(X)的参数类型,也同样为execute(X)的参数类型。 Y为onProgressUpdate(Y)的参数类型。 Z为    onPostExecute(Z)的参数类型。

3.doInBackground在后台,onProgressUpdate在前台。通过publishProgress(Y)传递后台数据到前台。


举例函数:

package com.android.weather.parse;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

import com.android.weather.db.Weathers;


public class ReadWeatherDataInternet {
	private static final String TAG = "ReadWeatherDataInternet";
	
	private static URL cityUrl = null;
	private static String cityStr = "Beijing";
		
	private Context mContext;
	private HttpResponed mHttpResponed;
	
	public ReadWeatherDataInternet(Context c) {
		mContext = c;
	}
	
	public void SetHttpConnectListener(HttpResponed responed){
		mHttpResponed = responed;
	}
	
	public void ParseURL(String city){
		
		ConnectivityManager connectivityManager = 
			(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkinfo = connectivityManager.getActiveNetworkInfo();		
        if (networkinfo==null) {
        	Log.d("Controller", "no active network");
        	mHttpResponed.respond(null,city,false);
        	
             return;
        }
        
		cityStr = city;
		InputStream is = readWeatherDataFromInternet();
		if(is != null){
			ParseTask task = new ParseTask();  
	        task.execute(is);  //参数个数是可变的,可以传0个,1个,2个或者更多,当调用这个函数系统就会自动去调用doInBackgound()函数
		}
		
		
	}
	
	class ParseTask extends AsyncTask<InputStream ,CurrentEntity, String> {//这三个参数对应的是excute(String),
        //onProgressUpdate(Integer),onPostResult(string)这三个方法里面的参数类型  
		// 可变长的输入参数,与AsyncTask.exucute()对应  
				 
		@Override  
		protected void onProgressUpdate(CurrentEntity... entity) {  //这个参数是接受publishProgress(Integer)的参数的
			mHttpResponed.respond(entity[0],cityStr,true);
		}
		
		@Override  
		protected String doInBackground(InputStream... in) {  //用来接受excute(String)里面的参数
			if(in == null){
				Log.d(TAG,"inputStream is null--------------------------");
			}
			SAXParserFactory spf = SAXParserFactory.newInstance();
	        			
	        SAXParser sp;
			try {
				sp = spf.newSAXParser();
				XMLReader reader = sp.getXMLReader();
				XMLHandler  handler = new XMLHandler();
		        reader.setContentHandler(handler);            
		
//		        URL url = new URL(Weathers.WEB_URI + URLEncoder.encode(city));
//		        InputStream is = url.openStream();
		        InputStreamReader isr = new InputStreamReader(in[0],"GBK");
				InputSource source = new InputSource(isr);
					
			    reader.parse(source);
		        
		        CurrentEntity currentWeather = handler.getCurrentWeather();
		    	
		        publishProgress(currentWeather);  //这个函数的参数的个数也是可以变化的		
				
			} catch (ParserConfigurationException e) {				
				e.printStackTrace();
			} catch (SAXException e) {				
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {				
				e.printStackTrace();
			} catch (IOException e) {				
				e.printStackTrace();
			}
	        
			return null;
		}   
		
		@Override  
		protected void onPostExecute(String result) {  //这个参数是接受doInBackgound()的返回值的
		// 返回HTML页面的内容  				
		}  
		
		@Override  
		protected void onPreExecute() {  
		// 任务启动,可以在这里显示一个对话框,这里简单处理  		
		}  		   
	}    

	private InputStream readWeatherDataFromInternet()  
    {          
        InputStream inStream = null;  
        try {  
        	cityUrl = new URL(Weathers.WEB_URI + URLEncoder.encode(cityStr,"gb2312"));
            Log.d(TAG,"------------------------------cityUrl = "+cityUrl);
            URLConnection connection = cityUrl.openConnection();  
            HttpURLConnection httpConnection = (HttpURLConnection)connection;  
            int responseCode = httpConnection.getResponseCode();  
            if(responseCode == HttpURLConnection.HTTP_OK)  
            { 
            	Log.d(TAG,"httpurlconnection is ok=============================");
                inStream = httpConnection.getInputStream();  
            }else{  
            	Log.d(TAG,"httpurlconnection is not ok=============================");
            }
        } catch (MalformedURLException e) {  
            Log.e(TAG,"MalformedURLException======================================");
            e.printStackTrace();  
            
            return null;
        } catch (IOException e) {  
            Log.e(TAG,"IOException=========================================="); 
            e.printStackTrace();
            
            return null;
        }  
        return inStream;  
    } 
	
	public interface HttpResponed{
		public void respond(CurrentEntity entity,String city,Boolean network);
	}
	
}

说明:XMLHandler为解析XML文件的一个类

 

Thread类使用:

			Thread saveRecordingThread = new Thread(){
				public void run(){
					 try {
			                Thread.sleep(5000);
			            } catch (InterruptedException e) {			               
			                e.printStackTrace();
			            }finally{
			            	saveRecording();
			            }					
				}
			};
			saveRecordingThread.start();



 

你可能感兴趣的:(android 线程之AsyncTask)