
子线程通知主线程更新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的,也不可以直接d出Toast(土司)。
3.
转载于:https://www.cnblogs.com/guoxinglei/p/3432229.HTML
总结以上是内存溢出为你收集整理的子线程全部内容,希望文章能够帮你解决子线程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)