通过URL,使用HttpURLConnection进行请求/响应,访问web服务器图片等资源。异常报错

package com.example.louisnetimage;

import com.example.service.ImageService;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText pathText;
	private ImageView imageView;
	private Button button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pathText = (EditText) this.findViewById(R.id.imagepath);
		imageView = (ImageView) this.findViewById(R.id.imageView);
		button = (Button) this.findViewById(R.id.button);

		button.setOnClickListener(new ButtonClickLister());
	}

	private final class ButtonClickLister implements View.OnClickListener {

		public void setImageView() {
			String path = pathText.getText().toString();
			byte[] data = null;
			try {
				data = ImageService.getImage(path);
				final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
						data.length);
				Looper.prepare();// 必须调用此方法,要不然会报错
				Message msg = new Message();
				msg.what = 0;
				msg.obj = bitmap;
				handler.sendMessage(msg);

			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				Toast.makeText(getApplicationContext(),
						"错误消息" + e.getMessage(), 1).show();
			}
		}

		@Override
		public void onClick(View v) {
			// TODO 自动生成的方法存根

			new Thread(new Runnable() {
				public void run() {
					setImageView();

				}
			}).start();
		}

	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				imageView.setImageBitmap((Bitmap) msg.obj);
			}

		}
	};

}



新API需要启用新线程才能使用出来显示图片

你可能感兴趣的:(通过URL,使用HttpURLConnection进行请求/响应,访问web服务器图片等资源。异常报错)