今天我们讲下Android中handler的使用,主要用途是从网络下载资源。
另外就是把网络图片下载到本地,如果本地有图片就从本地读取,否则就从网络下载。
代码中都有详细的注释:
package com.example.test_01;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
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.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener{
private Button btn;
private ImageView iv;
private String PATH = "https://www.baidu.com/img/bd_logo1.png";
//创建handler对象来处理消息
Handler handler = new Handler(){
//此方法在主线程中调用,可以用来刷新ui
public void handleMessage(android.os.Message msg) {
//这里对msg.what进行判断并进行相应的处理
if(msg.what == 1){
iv.setImageBitmap((Bitmap)msg.obj);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_download);
iv = (ImageView) findViewById(R.id.iv_icon);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
//获取写入图片的文件路径,getCacheDir()是写入内存
final File file = new File(getCacheDir(), getFileName(PATH));
//如果文件存在,就从文件中读取图片
if(file.exists()){
Log.i("main", "从本地读取的");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
iv.setImageBitmap(bitmap);
}
//如果文件不存在,就创建子线程从网络缓存图片到本地然后显示
else{
Log.i("main","从网络读取的");
Thread thread = new Thread(){
@Override
public void run() {
try {
URL url = new URL(PATH);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
//获取文件的写入流
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
//把is中的网络资源读取到数组buf中,读取完后is中就没有内容了
while((len = is.read(buf)) != -1){
fos.write(buf, 0, len);
}
fos.close();
//通过文件路径构建位图
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//获取消息对象
Message msg = handler.obtainMessage();
//消息对象可以携带数据
msg.obj = bitmap;
//这里是为了区分msg携带不同的数据
msg.what = 1;
//把消息发送至主线程的消息队列
handler.sendMessage(msg);
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
//获取图片保存到本地的文件名,一般以"dd.jpg"或"dd.png"结尾
//可以当作一个工具类
public String getFileName(String path){
//获取文件路径的最后一个"/"
int index = path.lastIndexOf("/");
//返回文件名的字符串
return path.substring(index + 1);
}
}
运行结果: