实现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);
- 实现android异步调用WEB API的方法
- 实现android异步调用WEB API的方法,并实现回调
- Java多线程实现异步调用的方法
- 异步调用Web服务方法
- 实现异步调用Web Service
- 实现异步调用 Web Service
- 百度地图js api 异步调用方法
- C# 异步实现方法调用
- PHP实现异步调用方法
- Web Service 的异步调用
- android AsyncTask异步调用方法
- android 中异步线程的实现方法
- Android实现异步的几种方法
- Android实现异步的几种方法
- Android实现异步的几种方法
- Android实现异步的几种方法
- ASP.NET MVC4中调用WEB API的四个方法
- ASP.NET MVC4中调用WEB API的四个方法
- 387. Taking mends no holes. 空谈无补
- 多级简易BOM
- char类型与Unicode编码
- Centos安装图形化界面
- CentOS 6网络配置
- 实现android异步调用WEB API的方法
- opencv的Mat中step的解释
- ruby的一些小技巧
- 如何将数据库由高版本降为低版本
- 关于ubuntu“下载软件仓库信息失败 检查您的网络连接“问题的解决办法
- 实现android异步调用WEB API的方法,并实现回调
- CodeSmith 使用教程(17) Merge策略
- volatile变量
- Eclipse下安装Aptana Studio 插件