添加访问网络的权限:<uses-permission android:name="android.permission.INTERNET"/>

package com.shz.imageviewer;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Build; public class MainActivity extends Activity { private ImageView iv;
private EditText txtPath; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); this.iv = (ImageView) this.findViewById(R.id.iv);
this.txtPath = (EditText) this.findViewById(R.id.txtPath);
} // Android新版系统中不允许UI处理比较耗时的操作(ANR),如果有耗时操作,可以通过开启一个子线程去处理;
// 只有UI线程可以更新view对象。 // 如果有多个子线程更新UI,更新UI完毕后,检查这个更新的操作是否在主线程的代码中执行的,
// 如果是主线程,则不会有问题
// 如果不是主线程,则会抛出异常:CalledFromWrongThreadException // 1.定义一个handler消息处理器
private Handler handler = new Handler(){ @Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Bitmap bitmap = (Bitmap)msg.obj;
iv.setImageBitmap(bitmap);
break;
case 2:
Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}; private void sendMessage(int what,Object obj)
{
Message msg = new Message();
msg.what = what;
msg.obj = obj;
handler.sendMessage(msg);
} public void click(View view) {
final String path = this.txtPath.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
return;
} // 2.开启一个子线程获取网络图片资源数据
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"); int code = conn.getResponseCode();
if ( code == 200) {
Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream()); // 3.利用handler消息处理器发送一条消息到主线程的MessageQueue消息队列中,主线程中
// 有一个消息轮询器Looper,此Looper会去不断的轮询MQ中的消息并
// 交给handler的handleMessage()方法去处理
sendMessage(1, bitmap);
} else {
sendMessage(2, "获取图片失败");
}
} catch (Exception e) {
e.printStackTrace();
sendMessage(2, "获取图片失败");
}
};
}.start();
}
}

通过HTTP访问网络资源-LMLPHP

05-06 04:15