2016.7.4关于线程的一些问题

来源:互联网 发布:seo域名查询 编辑:程序博客网 时间:2024/06/12 09:08

1.主线程概念

2.handler原理

3.使用handler完善

4.图片查看器




1.主线程的概念

(1)消息机制的写法 anr application not response

主线程(UI线程)

(2)如果在主线程中进行了耗时操作(连接网络,拷贝大数据)

(3)避免耗时操作--放到子线程

(4)在4.0以后谷歌强制要求连接网络不能再主线程中

(5)只有主线程才能更新UI




2.handler原理






3.使用handler完善案例

toast是一个view,不能在子线程中更新ui

Tost.makeText(getApplicationContext(),"请求消息不存在",1).show();

Ctrl+shift+x y   变大小写

规则:不管你什么版本的手机  只要做耗时的操作(比如连接网络  比如拷贝大的数据等等)就自己开一个子线程,获取数据后想要更新UI,就得使用handler就可以了。



public void click(View v) {

//[2.0]创建一个子线程
new Thread(){
public void run(){

try {
String path=et_path.getText().toString().trim();
URL url=new URL(path);

HttpURLConnection conn=(HttpURLConnection) url.openConnection();
//[2.4]发送GET请求  系统默认就是GET请求
conn.setRequestMethod("GET");
//[2.5]设置请求时间
conn.setConnectTimeout(5000);
//[2.6]获取服务器返回的状态吗
int code=conn.getResponseCode();
//[2.7]如果code==200 说明返回成功

if(code==200){

InputStream in=conn.getInputStream();

//[2.9]使用我们定义的工具类 把in转换成String

String content=StringTools.readStream(in);

//创建message对象
Message msg=new Message();
msg.obj=content;
msg.what=REQUESTSUCESS;

//拿着我们创建的handler 告诉系统 说我要跟新ui
handler.sendMessage(msg);
//发了一条消息 消息(msg)里把数据放到msg里handlemessage方法就会执行


//[2.9.1]把流里面的数据展示到textview上
//tv_result.setText(content);
}else{
//请求资源不存在 Toast是一个view 也不能在主线程更新ui
Message msg=new Message();
msg.what=1;//代表哪条消息
handler.sendMessage(msg);

}


} catch (Exception e) {

e.printStackTrace();
Message msg=new Message();
msg.what=REQUESTEXCEPTION;//代表那条消息
handler.sendMessage(msg);
}

};}.start();

}




//在主线程中进行判断 输出

private Handler handler=new Handler(){

//这个方法是在主线程里执行的 
public void handleMessage(android.os.Message msg){
//所以就可以在主线程里面更新UI了
//区分一下发送的是哪条消息

switch(msg.what){
case REQUESTSUCESS://代表请求成功
String content=(String)msg.obj;
tv_result.setText(content);
break;

case REQUESTNOTFOUND:
Toast.makeText(getApplicationContext(), "请求资源不存在", 0).show();

case REQUESTEXCEPTION://代表请求成功
Toast.makeText(getApplicationContext(), "服务器忙,请稍后再访问", 1).show();
break;
}

String content=(String) msg.obj;
tv_result.setText(content);

};
};



4.图片查看器

图片的显示控件

</ImageView>

创建一个子线程

new Thread(){


public void run(){

try {
String path=et_path.getText().toString().trim();
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code=conn.getResponseCode();


if(code==200){
InputStream in=conn.getInputStream();
Bitmap bitmap=BitmapFactory.decodeStream(in);
Message msg=Message.obtain();

msg.obj=bitmap;
handler.sendMessage(msg);

}

}


catch (Exception e) {

e.printStackTrace();

}

};}.start();


  在主线程中接收数据


private Handler handler=new Handler(){

public void handleMessage(android.os.Message msg){

Bitmap bitmap=(Bitmap) msg.obj;
tv_result.setImageBitmap(bitmap);

};
};








0 0
原创粉丝点击