android 典型应用之访问网络

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

2. 例程

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

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

](http://download.csdn.net/source/2650779)

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

_

  1. 核心代码及说明
    _ 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);
}
} _

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