Android 网络访问 线程注意事项

模拟一个 从网络中读取一个图片展示到imageView的操作:

注意事项1:

        URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

       执行此方法用来开辟一个URL请求,该请求在Android4.0版本以后需要放到子线程中实现,主线程已不支持httprequest请求(android2.3仍然支持此项)

        InputStream inputStream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// iv.setImageBitmap(bitmap);

        第三句则会报错 :android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

 注意事项2:  因为在子线程中不可以对view操作,因为view是在主线程创建的,需要在子线程中以消息的形式通知主线程

new Thread()
			{
				public void run()
				{
					try {
						URL url = new URL(path);
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						conn.setRequestMethod("GET");
						conn.setConnectTimeout(5000);
						conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Shuame)");
						int responseCode = conn.getResponseCode();
						if(responseCode==200)
						{
							InputStream inputStream = conn.getInputStream();
							Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//							iv.setImageBitmap(bitmap);
                                         //采用传送消息的模式 把view操作消息发给主线程
							Message msg = new Message();
							msg.what=CHANGE_UI;
							msg.obj=bitmap;
							handler.sendMessage(msg);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Toast.makeText(MainActivity.this, "访问网络失败",0).show();
					}
				}
			}.start();
主activity中定义handler:

private Handler handler =new Handler(){
		public void handleMessage(android.os.Message msg)
		{
			if(msg.what==CHANGE_UI)
			{
				iv.setImageBitmap((Bitmap) msg.obj);
			}
		};
	};


Android 网络访问 线程注意事项

      Android 网络访问 线程注意事项

       

Android 网络访问 线程注意事项

上一篇:AI制作漂亮的矢量凹凸印刷文字效果


下一篇:小米刷机