Webview访问移动网络的两种方法

效果如下 网络访问的两种查看方式
网页刷新的比较慢
我们来看代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="看网页"
        android:gravity="center"
        android:textSize="25dp"
        />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="viewpage"
        android:text="看网页" />
 <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="viewcode"
        android:text="看源码" />
 <WebView 
     android:id="@+id/page_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:visibility="gone"/>
 <TextView 
     android:id="@+id/code_tv"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="#ff00ff"
     android:minLines="8"/>
</LinearLayout>

下面来看activity的代码

public class Lookwebpage extends Activity {
    private WebView webview;
    private TextView textView;
    StringBuilder sBuilder = null;
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if(msg.what==1){
                String codeStr=(String) msg.obj;
                textView.setVisibility(View.VISIBLE);
                textView.setText(codeStr);
            }

        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lookwebpage);
        webview = (WebView) findViewById(R.id.page_view);
        textView = (TextView) findViewById(R.id.code_tv);
    }

    // 查看网页
    public void viewpage(View view) {
        webview.loadUrl("http://blog.csdn.net/tangsilian/article/details/51212193");
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                // 返回true则表明使用的是WebView
                return true;
            }
        });
        textView.setVisibility(View.INVISIBLE);
        webview.setVisibility(View.VISIBLE);

    }

    // 查看源码
    public void viewcode(View view) {
        // textView.setText(text);
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    URL url = new URL("http://blog.csdn.net/tangsilian?viewmode=contents");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setReadTimeout(5000);
                    connection.setRequestMethod("GET");
                    if(connection.getResponseCode()==200){
                        InputStream is = connection.getInputStream();
                        byte[] data=StreamUtil.parseInputStream(is);
                        String result=new String(data, "UTF-8");
                        Message message=new Message();
                        message.obj=result;
                        message.what=1;
                        handler.sendMessage(message);
                    }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }


        };
        new Thread(runnable).start();
    }
}

主要看两个点击事件

    // 查看网页
    public void viewpage(View view) {
        webview.loadUrl("http://blog.csdn.net/tangsilian/article/details/51212193");
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                // 返回true则表明使用的是WebView
                return true;
            }
        });
        textView.setVisibility(View.INVISIBLE);
        webview.setVisibility(View.VISIBLE);

    }

用网页查看的代码,主要是这一句

webview.loadUrl("http://blog.csdn.net/tangsilian/article/details/51212193");

查看源码的方法,新启动一个线程来处理从网页上接受到的数据

    public void viewcode(View view) {
        // textView.setText(text);
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    URL url = new URL("http://blog.csdn.net/tangsilian?viewmode=contents");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setReadTimeout(5000);
                    connection.setRequestMethod("GET");
                    if(connection.getResponseCode()==200){
                        InputStream is = connection.getInputStream();
                        byte[] data=StreamUtil.parseInputStream(is);
                        String result=new String(data, "UTF-8");
                        Message message=new Message();
                        message.obj=result;
                        message.what=1;
                        handler.sendMessage(message);
                    }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }


        };
        new Thread(runnable).start();
    }

先用HttpURLConnection连接,收到连接成功的返回码200之后,发送message到主线程的message队列,再交给主线程的handlemessage来处理。
工具类StreamUtil的代码

public class StreamUtil {
    /**把输入流转为字节数组
     * 
     * @param is
     * @return
     */
    public static byte[] parseInputStream(InputStream is) throws Exception{
        // TODO Auto-generated method stub
        // 内存流, 字节数组输出流
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len=-1;
        while((len=is.read(buffer))!=-1){ //当没有到文档的结尾
            baos.write(buffer, 0, len);
        }
        baos.close();//内存流关闭后,还可以访问,只是不能再添加数据
        is.close();
        return baos.toByteArray();
    }

}

工具类就是将输入流转化为字节数组的。
最后不来忘了在 manifest配置文件中设置网络访问权限

<uses-permission android:name="android.permission.INTERNET"/>
posted @ 2016-04-29 23:44  Tesi1a  阅读(178)  评论(0编辑  收藏  举报