zoukankan      html  css  js  c++  java
  • Android网络编程1

    最近在自学Android开发,从这篇开始作为我学习android开发的笔记,来记录学习过程中遇到的问题点和其解决的方法;

    Ui界面代码

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     xmlns:tools="http://schemas.android.com/tools"
     4     android:layout_width="match_parent"
     5     android:layout_height="match_parent"
     6     android:paddingBottom="@dimen/activity_vertical_margin"
     7     android:paddingLeft="@dimen/activity_horizontal_margin"
     8     android:paddingRight="@dimen/activity_horizontal_margin"
     9     android:paddingTop="@dimen/activity_vertical_margin"
    10     tools:context="com.example.lidezhen.myapplication.MainActivity"
    11     android:orientation="vertical">
    12 <EditText
    13     android:layout_width="match_parent"
    14     android:layout_height="wrap_content"
    15     android:id="@+id/text1"
    16     android:hint="请是输入网址"/>
    17     <Button
    18         android:layout_width="wrap_content"
    19         android:layout_height="wrap_content"
    20         android:text="打开"
    21             android:onClick="Onclick"/>
    22     <TextView
    23         android:layout_width="match_parent"
    24         android:layout_height="match_parent"
    25         android:id="@+id/tv1"
    26         android:hint="这是源码"/>
    27 
    28 </LinearLayout>

    界面后台代码

    package com.example.lidezhen.myapplication;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class MainActivity extends AppCompatActivity {
    
        EditText et;
        TextView tv;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
             et= (EditText) findViewById(R.id.text1);
             tv= (TextView) findViewById(R.id.tv1);
    //        if (android.os.Build.VERSION.SDK_INT > 9) {
    //            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    //            StrictMode.setThreadPolicy(policy);
    //        }
        }
        public void Onclick(View v)
        {
    
    
            try {
                String path=et.getText().toString();
    
                URL url = new URL(path);
                 HttpURLConnection con = (HttpURLConnection) url.openConnection();
                int code=con.getResponseCode();
                if (code==200)
                {
    
                    InputStream stream = con.getInputStream();
                    ByteArrayOutputStream os=new ByteArrayOutputStream();
                    int len=-1;
                    byte[] buff=new byte[1024];
                    while ( (len=stream.read(buff))!=-1)
                    {
                       os.write(buff,0,len);
    
                    }
                    tv.setText(os.toString());
                }
            } catch (Exception e) {
                Log.e("错误",e.toString());
            }
    
        }
    }编译并执行程序
     

      程序报错

    07-20 02:30:00.361 15820-15820/com.example.lidezhen.myapplication E/错误: android.os.NetworkOnMainThreadException

    错误原因:Android在4.0之前的版本 支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,也就是说访问网络的代码不能写在主线程中了(我的虚拟机是android6.0的)

    错误解决方法1:

    在onCreate方法中添加如下代码

     if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
               StrictMode.setThreadPolicy(policy);
            }

    方法2:在点击事件里面添加多线程

    public void Onclick(View v)
        {
            new Thread() {
                @Override
                public void run() {
                    try {
                        String path=et.getText().toString();
    
                        URL url = new URL(path);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        int code=con.getResponseCode();
                        if (code==200)
                        {
    
                            InputStream stream = con.getInputStream();
                            ByteArrayOutputStream os=new ByteArrayOutputStream();
                            int len=-1;
                            byte[] buff=new byte[1024];
                            while ( (len=stream.read(buff))!=-1)
                            {
                                os.write(buff,0,len);
    
                            }
                            tv.setText(os.toString());
                        }
                    } catch (Exception e) {
                        Log.e("错误",e.toString());
                    }
    
    
                }
            }.start();

    程序执行成功

     这样开新线程后程序还是报错

    07-20 02:49:12.203 32712-707/com.example.lidezhen.myapplication E/错误: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

    意思就是新的线程不能操作界面控件

    解决方法:添加handeler

    package com.example.lidezhen.myapplication;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class MainActivity extends AppCompatActivity {
    
        EditText et;
        TextView tv;
        @Override
                protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
             et= (EditText) findViewById(R.id.text1);
             tv= (TextView) findViewById(R.id.tv1);
    
    //       if (android.os.Build.VERSION.SDK_INT > 9) {
    //            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    //           StrictMode.setThreadPolicy(policy);
    //        }
        }
        public void Onclick(View v)
        {
    
            new Thread() {
                @Override
                public void run() {
                    try {
    
    
                        String path=et.getText().toString();
                        URL url = new URL(path);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        int code=con.getResponseCode();
                        if (code==200)
                        {
    
                            InputStream stream = con.getInputStream();
                            ByteArrayOutputStream os=new ByteArrayOutputStream();
                            int len=-1;
                            byte[] buff=new byte[1024];
                            while ( (len=stream.read(buff))!=-1)
                            {
                                os.write(buff,0,len);
    
                            }
    //                        tv.setText(os.toString());
                            Message msg=new Message();
                            msg.obj=os.toString();
                            handler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        Log.e("错误",e.toString());
                    }
    
    
                }
            }.start();
    
    
    
    
        }
       Handler handler=new Handler(){
           public void handleMessage(Message msg) {
               String s=(String)msg.obj;
             tv.setText(s);
           }
    
       };
    
    
    }

    这样就不会再报异常

  • 相关阅读:
    阿里规范
    阿里规范
    阿里规范
    sql 优化步骤
    事务的并发问题:脏读、幻读和不可重复读
    Hive 常见面试题(二)
    yield 的使用
    Java 线程状态
    Lambda 表达式推演全过程
    IDEA 代码自动补全/自动联想 功能
  • 原文地址:https://www.cnblogs.com/lidezhen/p/5687475.html
Copyright © 2011-2022 走看看