现在的位置: 首页 > 综合 > 正文

在Android线程中设置控件的值会报错

2018年09月15日 ⁄ 综合 ⁄ 共 2275字 ⁄ 字号 评论关闭

在Android线程中设置控件的值一般会与Handler联合使用,如下:

package com.bbk.android; 

import java.io.FilterInputStream;
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
   
import android.app.Activity; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.ImageView; 
import android.widget.Toast;
 
/** 
 * @ClassName: PicActivity 
 * @Description: 显示网络图片
 */

public class PicActivity extends Activity { 
    /** Called when the activity is first created. */ 
     String imageUrl = "http://content.52pk.com/files/100623/2230_102437_1_lit.jpg";   
     ImageView imView;
     URL myFileUrl = null;   
     static Bitmap bitmap = null;
     private  Handler handler;
     
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_pic); 
        
        handler = new Handler(){
public  void handleMessage(android.os.Message msg) {
//处理消息
if (msg.what == 0x01) {
Log.e("aaaa3",bitmap+"");
imView = (ImageView) findViewById(R.id.imageView);   
           imView.setImageBitmap(bitmap);

}

};
};
        
        returnBitMap();
       
    } 
    
    /**
* @ClassName: PicThread
* @Description: 链接网络并下载图片线程
* @注:在子线程中不能对控件进行操作,因此联合Handler一起使用
*/
    private class PicThread  extends Thread{
    @Override
public void run() {
Looper.prepare();

  try {   
           myFileUrl = new URL(imageUrl);   
       } catch (MalformedURLException e) {   
           e.printStackTrace();   
       }   
       try {   
           HttpURLConnection conn = (HttpURLConnection) myFileUrl   
             .openConnection();   
           conn.setDoInput(true);   
           conn.connect();   
           
           InputStream is = conn.getInputStream(); 
           Log.e("aaaa1",is+"");
           bitmap = BitmapFactory.decodeStream(new PatchInputStream(is));
           Log.e("aaaa2",bitmap+"");
           
           handler.sendEmptyMessage(0x01);
           is.close();   
       } catch (IOException e) {   
             e.printStackTrace();   
       }  

Looper.loop();
}
    }
    
    public class PatchInputStream extends FilterInputStream{

protected PatchInputStream(InputStream in) {
super(in);
// TODO Auto-generated constructor stub
}

public long skip(long n)throws IOException{
long m=0l;
while(m<n){
long _m=in.skip(n-m);
if(_m==0l){
break;
}
m+=_m;
}
return m;
}

}
    
    public void returnBitMap(){ 
        
    new PicThread().start();
    }   
}

抱歉!评论已关闭.