1.     android 网络
android
访问网络需要设置权限, java 提供了很好的封装

2.     例程

1)         功能
从网上下载文本文件,并使用 textview 控件显示其内容

2)         可从此处下载可独立运行的代码
http://download.csdn.net/source/2650779

3)         权限
AndroidManifest.xml 中需要加入访问网络的权限
< uses-permission android:name =" android.permission.INTERNET" />

4)         核心代码及说明
package com.android.mynet;

import android.app.Activity;
import android.os.Bundle;
import java.io.*;
import java.net.*;
import org.apache.http.util.ByteArrayBuffer;
import android.widget.TextView;
import android.util.Log;

public class MyNetActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        connect();
    }

    public void connect()
    {
        String myString = null;
        try {
            URL myURL = new URL("http://www.google.com/robots.txt");
            URLConnection ucon = myURL.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte)current);
            }
            myString = new String(baf.toByteArray());
        } catch (Exception e) {
            myString = e.getMessage();
        }
         TextView tv;
        tv = (TextView) this.findViewById(R.id.tv1);
        tv.setText(myString);
    }
}

5)         参考 :
http://labs.chinamobile.com/mblog/103798_25897

 

posted on 2010-08-27 13:20  xieyan0811  阅读(18)  评论(0编辑  收藏  举报