子线程

 

 

 

子线程通知主线程更新UI

 

 

AndroidManifest.xml文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android_enjoy_thread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
  <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
View Code

 

 

xml文件:

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

   <ScrollView 
       android:id="@+id/scroll"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_weight="1"
       >
       
        <TextView
            android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hello_world"
      />
   </ScrollView>
    
    <EditText 
        android:layout_marginLeft="10dip"
        android:id="@+id/edittext"
        android:layout_width="300dip"
        android:layout_height="wrap_content"
        android:hint="请输入网址http://:"
        />
    <Button 
        android:layout_marginLeft="105dip"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击我"/>

</LinearLayout>
View Code

java文件:

1.无子线程,无Handler处理器:

 java代码:

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    private Button btn;
    private EditText et ;
    private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button)findViewById(R.id.button);
        et = (EditText)findViewById(R.id.edittext);
        tv = (TextView)findViewById(R.id.textview);
        btn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        String path = et.getText().toString();
        switch (v.getId()) {
        case R.id.button:
            if (TextUtils.isEmpty(path)) {
                Toast.makeText(getApplicationContext(), "请输入网址", 1).show();
            }
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                int code = conn.getResponseCode();
                if (code == 200) {
                    InputStream input = conn.getInputStream();
                    String text = InputStreamTools(input);
                    tv.setText(text);
                }else{
              Toast.makeText(getApplicationContext(), "输入网站不存在", 1).show();
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        }
    }
    
    //自定义一个读取输入流的方法
    public String InputStreamTools(InputStream input){
        //创建BufferedReader对象 读取一行
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        //创建ByteArrayOutputStream对象
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String line = null ;
        try {
            //边读边写,将内容写到ByteArrayOutputStream对象out中
            while((line = br.readLine())!=null){
                out.write(line.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将流转化为String类型,返回String类型
        return out.toString();
    }
}
View Code

2.有子线程,无Handler处理器: java代码:

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
 protected static final int PATH_NULL = 1;
protected static final int PATH_EXIST = 2;
protected static final int PATH_ERROR = 3;
private Button btn;
 private EditText et ;
 private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button)findViewById(R.id.button);
        et = (EditText)findViewById(R.id.edittext);
        tv = (TextView)findViewById(R.id.textview);
        btn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button:
            new Thread(new Runnable() {
                String path = et.getText().toString();
                @Override
                public void run() {
                    if (TextUtils.isEmpty(path)) {
                        System.out.println("请输入网址");
                    }
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
                        conn.setRequestMethod("GET");//设置联网方式为GET方式
                        conn.setConnectTimeout(5000);//设置网络连接时间
                        int code = conn.getResponseCode();
                        if (code == 200) {//如果code的值为200,则表示联网成功,path有效
                            InputStream input = conn.getInputStream();
                            String text = InputStreamTools(input);
                            System.out.println("网站内容:"+text);
                        }else {
                            System.out.println("输入网址错误!");
                        }
                    } catch (Exception e) {
                        
                    }
                    
                }
            }).start();
            break;
        }
    }
    
    //自定义一个读取输入流的方法
    public String InputStreamTools(InputStream input){
        //创建BufferedReader对象 读取一行
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        //创建ByteArrayOutputStream对象
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String line = null ;
        try {
            //边读边写,将内容写到ByteArrayOutputStream对象out中
            while((line = br.readLine())!=null){
                out.write(line.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将流转化为String类型,返回String类型
        return out.toString();
    }
}
View Code

 

3.有子线程,有Handler处理器:

java代码:

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
 protected static final int PATH_NULL = 1;
protected static final int PATH_EXIST = 2;
protected static final int PATH_ERROR = 3;
private Button btn;
 private EditText et ;
 private TextView tv;
 private Handler handler = new Handler(){

    /* (non-Javadoc)
     * @see android.os.Handler#handleMessage(android.os.Message)
     */
    @Override
    public void handleMessage(Message msg) {
         switch (msg.what) {
        case PATH_NULL:
            Toast.makeText(getApplicationContext(), "请输入网址", 1).show();
            break;
        case PATH_EXIST:
            String text = (String) msg.obj;
            tv.setText(text);
            break;
        case PATH_ERROR:
            Toast.makeText(getApplicationContext(), "输入网站不存在", 1).show();
            break;

        default:
            break;
        }
        super.handleMessage(msg);
    }
     
     
 };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button)findViewById(R.id.button);
        et = (EditText)findViewById(R.id.edittext);
        tv = (TextView)findViewById(R.id.textview);
        btn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button:
            new Thread(new Runnable() {
                String path = et.getText().toString();
                @Override
                public void run() {
                    if (TextUtils.isEmpty(path)) {
                        Message msg = Message.obtain();
                        msg.what = PATH_NULL;
                        handler.sendMessage(msg);
                    }
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
                        conn.setRequestMethod("GET");//设置联网方式为GET方式
                        conn.setConnectTimeout(5000);//设置网络连接时间
                        int code = conn.getResponseCode();
                        if (code == 200) {//如果code的值为200,则表示联网成功,path有效
                            InputStream input = conn.getInputStream();
                            String text = InputStreamTools(input);
                            Message msg = Message.obtain();
                             msg.obj = text;
                             msg.what = PATH_EXIST;
                            handler.sendMessage(msg);
                        }else {
                            Message msg = Message.obtain();
                            msg.what = PATH_ERROR;
                            handler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        
                    }
                    
                }
            }).start();
            break;
        }
    }
    
    //自定义一个读取输入流的方法
    public String InputStreamTools(InputStream input){
        //创建BufferedReader对象 读取一行
        BufferedReader br = new BufferedReader(new InputStreamReader(input));
        //创建ByteArrayOutputStream对象
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String line = null ;
        try {
            //边读边写,将内容写到ByteArrayOutputStream对象out中
            while((line = br.readLine())!=null){
                out.write(line.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将流转化为String类型,返回String类型
        return out.toString();
    }
}
View Code

注意:1.AndroidManifest.xml中要配置访问网络的权限:<uses-permission android:name="android.permission.INTERNET"/>

         2.为了避免线程争抢产生的安全隐患,google工程师在设计Android系统的时候,只有主线程才可以修改UI,子线程是不可以直接修改UI的,也不可以直接弹出Toast(土司)。

        3.

转载于:https://www.cnblogs.com/guoxinglei/p/3432229.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值