Android开发——实现数字时钟

前言

在最近的项目当中,我遇到一个在界面中实现系统数字时钟的需求。一看这个其实挺简单的,开个一个子线程获取当前的系统时间睡眠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开发的小伙伴有帮助,为自己打个小广告哈!下面是我的公众号的图片,我会经常更新一下技术干货或者开发踩坑历程,欢迎大家关注我!
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值