前言
在最近的项目当中,我遇到一个在界面中实现系统数字时钟的需求。一看这个其实挺简单的,开个一个子线程获取当前的系统时间睡眠1分钟发送当前时间,然后利用Handler去修改当前显示的时间,直接撸代码。
第一种:Handler+Thread
// 初始化方法
@Override
public void init() {
// 时间变化
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
tevtView.setText((String) msg.obj);
}
};
Threads thread = new Threads();
thread.start();
}
class Threads extends Thread {
@Override
public void run() {
try {
while (true) {
@SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String str = sdf.format(new Date());
handler.sendMessage(handler.obtainMessage(100, str));
Thread.sleep(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这样能正常实现功能,但是new Thread就是一个定时炸弹,在我的项目炸了。由于我很多页面都有用到这个时钟功能,内存泄漏了。
第二种:使用广播来实现
// 初始化方法
@Override
public void init() {
// 新时间
@SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
tevtView.setText(sdf.format(new Date()));
// 更新时间的广播
IntentFilter filter=new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
registerReceiver(receiver,filter);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
assert action != null;
if (action.equals(Intent.ACTION_TIME_TICK)) {
@SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
tevtView.setText(sdf.format(new Date()));
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
// 注销广播
unregisterReceiver(receiver);
}
总结
推荐使用第二种方法来实现时钟功能,性能方面第二种会比第一种好,使用第二种方法之后界面的流畅程度有了明显的提高。希望对Android开发的小伙伴有帮助,为自己打个小广告哈!下面是我的公众号的图片,我会经常更新一下技术干货或者开发踩坑历程,欢迎大家关注我!