Android文档学习05_网络1

反向地理编码是把处理经纬度坐标转换为人们可以读取的地址信息。这里使用的是Geocoder API


大多数网络连接的Android应用使用HTTP发送和接受数据,Android包括两个HTTP客户端:HttpURLConnection和ApacheHttpClient,它们支持HTTPS,流上传和下载


检查网络连接


ConnectivityManager connMgr = (ConnectivityManager) 
        getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        // 获取数据
    }...



网络操作涉及不可预知的延迟,为了防止不良的用户体验,通常的做法是从UI中独立出线程去执行网络连接操作。AsyncTask类提供了最简单的从UI线程中独立出一个新任务的方式。


if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadWebpageText().execute(stringUrl);
        } else {
            textView.setText("No network connection available.");
        }



// 使用AsyncTask创建一个独立于主UI线程之外的任务. 并使用URL字符串创建一个HttpUrlConnection对象。 
     // 一旦连接建立,AsyncTask则将网页内容作为一个InputStream对象进行下载。
     // 最终,InputStream对象会被转换为一个字符串对象,并被AsyncTask的onPostExecute方法显示在UI上。
     private class DownloadWebpageText extends AsyncTask {
        @Override
        protected String doInBackground(String... urls) {
 
            // 参数来自execute(),调用params[0]得到URL
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "无法获取网页,URL可能无效!Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute显示AsyncTask结果.
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
       }
    }


// 给一个URL,建立HttpUrlConnection对象并作为流对象(InputStream)获取网页数据,最后返回一个字符串。
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // 先显示获取到的前500个字节
    // 网页内容
    int len = 500;
 
    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // 开始查询
        conn.connect();

//getResponseCode()方法返回的是连接状态码
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();
 
        // 将InputStream转化为string
        String contentAsString = readIt(is, len);
        return contentAsString;
 
    // 确保当app用完InputStream对象后关闭它。
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}
 


下载了一个图像数据,你可能要将其转码然后像以下方式显示:

InputStream is = null;
...
Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = (ImageView) findViewById(R.id.image_view);

imageView.setImageBitmap(bitmap);



将InputStream对象转换为String(字符对象),然后activity在Ui中显示该字符串。


// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");        
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}









转载于:https://my.oschina.net/u/2288345/blog/367771

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值