通过一个通过网址查看图片的案例来说明handler和onUiThread这两种方法
mainactivity.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="https://www.baidu.com/img/bd_logo1.png?where=super"
android:hint="请输入查看的图片网址" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="查看" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
这里输入框内有一个默认网址,目标是点击“查看”按钮,在按钮下方会显示图片,效果图:
1.使用handler
MainActivity.java:
package com.learn.project_4_2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView iv;
private EditText et_path;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Bitmap bitmap = (Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
iv = (ImageView) findViewById(R.id.iv);
}
//【2】
public void click(View v){
//开辟子线程
new Thread(){
public void run(){
try {
File file = new File(getCacheDir(), "test.png");
//判断图片是否已经被缓存
if(file.exists()&&file.length()>0){
//使用缓存图片
System.out.println("使用缓存图片");
Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//把cacheBitmap 显示到iv上
Message msg = Message.obtain();
msg.obj= cacheBitmap;
handler.sendMessage(msg);
}
else{
System.out.println("第一次访问网络查看图片");
//【2.1】获取访问图片的路径
String path = et_path.getText().toString().trim();
//【2.2】创建URL对象
URL url = new URL(path);
//【2.3】获取httpurlconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//【2.4】设置请求的方式
conn.setRequestMethod("GET");
//【2.5】设置超时事件
conn.setConnectTimeout(5000);
//【2.6】获取服务器返回的状态码
int code = conn.getResponseCode();
if(code==200){
//【2.7】获取图片的数据,不管是什么数据。都是以流的形式返回
InputStream in = conn.getInputStream();
//【2.7.1】缓存图片 谷歌给我们提供了一个缓存目录
FileOutputStream fos = new FileOutputStream(file);
int len =1;
byte[] buffer =new byte[1024];
while((len=in.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
in.close();
//【2.8】通过位图工厂获取bitmap
//Bitmap bitmap = BitmapFactory.decodeStream(in);//位图 bitmap
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg =Message.obtain();//使用Message的静态方法obtain可以减少对象的创建
msg.obj = bitmap;
handler.sendMessage(msg);//发消息
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
2.使用runOnUiThread
MainActivity:
package com.learn.project_4_3;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.learn.project_4_3.R;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView iv;
private EditText et_path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
iv = (ImageView) findViewById(R.id.iv);
}
//【2】点击按钮,查看图片
public void click(View v){
new Thread(){
public void run(){
try {
File file = new File(getCacheDir(), "test.png");
//判断图片是否已经被缓存
if(file.exists()&&file.length()>0){
//使用缓存图片
System.out.println("使用缓存图片");
final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//把cacheBitmap 显示到iv上
runOnUiThread(new Runnable() {
public void run() {
iv.setImageBitmap(cacheBitmap);
}
});
}
else{
System.out.println("第一次访问网络查看图片");
//【2.1】获取访问图片的路径
String path = et_path.getText().toString().trim();
//【2.2】创建URL对象
URL url = new URL(path);
//【2.3】获取httpurlconnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//【2.4】设置请求的方式
conn.setRequestMethod("GET");
//【2.5】设置超时事件
conn.setConnectTimeout(5000);
//【2.6】获取服务器返回的状态码
int code = conn.getResponseCode();
if(code==200){
//【2.7】获取图片的数据,不管是什么数据。都是以流的形式返回
InputStream in = conn.getInputStream();
//【2.7.1】缓存图片 谷歌给我们提供了一个缓存目录
FileOutputStream fos = new FileOutputStream(file);
int len =1;
byte[] buffer =new byte[1024];
while((len=in.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
in.close();
//【2.8】通过位图工厂获取bitmap
//Bitmap bitmap = BitmapFactory.decodeStream(in);//位图 bitmap
final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//runOnUiThread(Runnable action),不管在什么位置调用这个方法,action都会运行在UI线程
runOnUiThread(new Runnable() {
public void run() {
iv.setImageBitmap(bitmap);
}
});
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
使用handler和runOnUiThread的区别
【1】如果仅仅需要更新UI,那么就用runOnUiThread这个API就行
【2】有的时候只能用handler,因为可能需要通过handler 发送消息 携带数据 这时候必须要用handler