实现android异步调用WEB API的方法

来源:互联网 发布:人民搜索网络股份公司 编辑:程序博客网 时间:2024/06/14 13:12

在一般应用中我们很多时候都会遇到利用网络请求实现和客户交互的操作,由于网络的请求需要或长或短的时间等待,所以我们一般会把显示界面和网络请求取得数据的操作放在不同的线程上操作,把界面的操作放在主线程,而从网络取得数据的操作就放在另外一个子线程中操作,网上说明这个实现方法的资料过于贫乏,所以我把实验代码贴出来

下面的类使用一个单独的线程从主界面线程的HTTP调用Android的AsyncTask。事实上,在较新版本的Android上你是无法在主线程上调用的,你会得到一个异常 android.os.networkonmainthreadexception

public class ApiCall extends AsyncTask {    private String result;    protected Long doInBackground(URL... urls) {int count = urls.length;    long totalSize = 0;    StringBuilder resultBuilder = new StringBuilder();        for (int i = 0; i < count; i++) {        try {            // Read all the text returned by the server                InputStreamReader reader = new InputStreamReader(urls[i].openStream());                BufferedReader in = new BufferedReader(reader);                String resultPiece;                while ((resultPiece = in.readLine()) != null) {                resultBuilder.append(resultPiece);                }                in.close();             } catch (MalformedURLException e) {             e.printStackTrace();             } catch (IOException e) {             e.printStackTrace();             }             // if cancel() is called, leave the loop early             if (isCancelled()) {             break;             }         }         // save the result         this.result = resultBuilder.toString();         return totalSize;     }    protected void onProgressUpdate(Integer... progress) {        // update progress here    }// called after doInBackground finishes    protected void onPostExecute(Long result) {     Log.v("result, yay!", this.result);    }}
调用方法很简单,如下:

URL url = null;try {    url = new URL("http://search.twitter.com/search.json?q=@justinjmcc");} catch (MalformedURLException e) {    e.printStackTrace();}new ApiCall().execute(url);




	
				
		
原创粉丝点击