您的位置:首页 > 移动开发 > Android开发

android实现联网小例子,刚学习与大家分享

2011-07-14 15:52 471 查看
首先是xml内容: 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/address"
    android:text="http://google.com"
    />
    <Button android:id="@+id/buttongo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="go!"
    />
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:textColor="#000000"
    android:id="@+id/pagetext"
    />
</LinearLayout>
 
java类
package net.blog.vtion;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GetWebPage extends Activity{
    Handler h;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  final EditText etext=(EditText)findViewById(R.id.address);
        final TextView tview=(TextView)findViewById(R.id.pagetext);
    
        this.h=new Handler(){
   @Override
   public void handleMessage(Message msg) {
    switch(msg.what){
          case 0:
           tview.append((String)msg.obj);
           break;
          }
    super.handleMessage(msg);
   }
         
        };
         Button button=(Button)findViewById(R.id.buttongo);
        button.setOnClickListener(new Button.OnClickListener(){
         
         
   @Override
   public void onClick(View v) {
    try{
     tview.setText("");
           URL url=new URL(etext.getText().toString());
           URLConnection conn=url.openConnection();
           BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream()));
           String line="";
           while((line=rd.readLine())!=null){
            Message lmsg;
            lmsg=new Message();
            lmsg.obj=line;
            lmsg.what=0;
            GetWebPage.this.h.sendMessage(lmsg);
           }
          }catch(Exception e){
           
          }
   }
   
        });
    }
 }
 最后一定要记得
manfest里写权限
 <uses-permission android:name="android.permission.INTERNET"/> 
 
里面用到什么直接查看api即可!
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息