对安卓中Handle机制的一些见解
2016-02-03 10:59
711 查看
消息队列机制
(1)主线程创建时,系统会同时创建消息队列对象(MessageQueue)和消息轮询器对象(Looper)
(2)轮询器的作用,就是不停的检测消息队列中是否有消息(Message)
(3)消息队列一旦有消息,轮询器会把消息对象传给消息处理器(Handler),处理器会调用handleMessage方法来处理这条消息,handleMessage方法运行在主线程中,所以可以刷新ui
总结:
(1)只要消息队列有消息,handleMessage方法就会调用
(2)子线程如果需要刷新ui,只需要往消息队列中发一条消息,触发handleMessage方法即可
(3) 子线程使用处理器对象的sendMessage方法发送消息
下面以下载图片做一个实例:
public class MainActivity extends Activity {
private static final String ADDRESS = "http://192.168.1.105:8080/g.jpg";
private static final int TIMEOUT = 5000;
private static ImageView iv;
private static MainActivity ma;
private static Handler handle = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
Bitmap bitmap = (Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
break;
case 0:
Toast.makeText(ma, "加载失败", 0).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
}
public void btnOnClicked(View v) {
// 首先判断图片文件在不在手机缓存里
final File file = new File(InternalStorageUtils.getInternalFilesDir(this), getFileName(ADDRESS));
if (file.exists()) {
Log.i("mtag", "图片已经存在");
Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
iv.setImageBitmap(map);
} else {
// 开启子线程进行图片的下载以及缓存
new Thread() {
@Override
public void run() {
HttpURLConnection conn = null;
try {
URL url = new URL(ADDRESS);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
conn.setRequestMethod("GET");
conn.connect();
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 保存到内部存储中
InternalStorageUtils.saveFileToInternalFilesDir(MainActivity.this,
readFromStream(conn.getInputStream()), getFileName(ADDRESS));
// 第一次读完后InputStreame里没有数据了
Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = handle.obtainMessage();
msg.obj = map;
msg.what = 1;
handle.sendMessage(msg);
} else {
Message msg = handle.obtainMessage();
msg.what = 0;
handle.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
}.start();
}
}
// 将文件输入流写到字节数组输出流中
private byte[] readFromStream(InputStream in) {
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
bos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
return bos.toByteArray();
}
// 获取文件的名字
private String getFileName(String address) {
int index = address.lastIndexOf("/");
return address.substring(index + 1);
}
}
(1)主线程创建时,系统会同时创建消息队列对象(MessageQueue)和消息轮询器对象(Looper)
(2)轮询器的作用,就是不停的检测消息队列中是否有消息(Message)
(3)消息队列一旦有消息,轮询器会把消息对象传给消息处理器(Handler),处理器会调用handleMessage方法来处理这条消息,handleMessage方法运行在主线程中,所以可以刷新ui
总结:
(1)只要消息队列有消息,handleMessage方法就会调用
(2)子线程如果需要刷新ui,只需要往消息队列中发一条消息,触发handleMessage方法即可
(3) 子线程使用处理器对象的sendMessage方法发送消息
下面以下载图片做一个实例:
public class MainActivity extends Activity {
private static final String ADDRESS = "http://192.168.1.105:8080/g.jpg";
private static final int TIMEOUT = 5000;
private static ImageView iv;
private static MainActivity ma;
private static Handler handle = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
Bitmap bitmap = (Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
break;
case 0:
Toast.makeText(ma, "加载失败", 0).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
}
public void btnOnClicked(View v) {
// 首先判断图片文件在不在手机缓存里
final File file = new File(InternalStorageUtils.getInternalFilesDir(this), getFileName(ADDRESS));
if (file.exists()) {
Log.i("mtag", "图片已经存在");
Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
iv.setImageBitmap(map);
} else {
// 开启子线程进行图片的下载以及缓存
new Thread() {
@Override
public void run() {
HttpURLConnection conn = null;
try {
URL url = new URL(ADDRESS);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
conn.setRequestMethod("GET");
conn.connect();
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 保存到内部存储中
InternalStorageUtils.saveFileToInternalFilesDir(MainActivity.this,
readFromStream(conn.getInputStream()), getFileName(ADDRESS));
// 第一次读完后InputStreame里没有数据了
Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = handle.obtainMessage();
msg.obj = map;
msg.what = 1;
handle.sendMessage(msg);
} else {
Message msg = handle.obtainMessage();
msg.what = 0;
handle.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
}.start();
}
}
// 将文件输入流写到字节数组输出流中
private byte[] readFromStream(InputStream in) {
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
bos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
return bos.toByteArray();
}
// 获取文件的名字
private String getFileName(String address) {
int index = address.lastIndexOf("/");
return address.substring(index + 1);
}
}
相关文章推荐
- 【Android 分享】ShareSDK微信分享详解
- 直接拿来用!最火的Android开源项目(一)
- Android开发项目经验
- Android中显示gif动态图片
- android源码项目
- Android大牛
- Spring Aop Aspectj切入点语法详解
- 探索Handler机制原理
- 有关Loader加载器的使用方法和总结
- HDU 1711 Number Sequence(kmp模板)
- HDU 3746 Cyclic Nacklace (kmp求循环节)
- Oracle 12c RAC 到单机实例 DATAGUARD搭建
- 浅谈如何在android studio上正确使用svn?
- ASP.NET 系列:单元测试之Log4Net
- 关于AJAX跨域调用ASP.NET MVC或者WebAPI服务的问题及解决方案
- asp.net mvc(模式)和三层架构(BLL、DAL、Model)的联系与区别
- [译] ASP.NET 生命周期 – ASP.NET 请求生命周期(四)
- 个人笔记 asp 10 asp随机数
- Raspbian 2019-06-20 发布,基于即将发布的Debian 10
- raspberrypi监控室内温度