Android监听系统时间变化(笔记)

1. 注册广播

IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        registerReceiver(mTimeUpdateReceiver, filter);

接口实现:

BroadcastReceiver mTimeUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null)return;
            String action = intent.getAction();
            if (action == null || action.isEmpty())return;

            if (action.equals(Intent.ACTION_TIME_TICK)) {
                //系统每1分钟发送一次广播
                updateTimeUi();
            } else if (action.equals(Intent.ACTION_TIME_CHANGED)) {
                //系统手动更改时间发送广播
                updateTimeUi();
            }
        }
    };

监听时间个改变,再通过Date类获取时间

DecimalFormat TwoInteger = new DecimalFormat("00") ;//这个类用于规范显示时间,选择性使用
    private void updateTimeUi() {

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        String sim = dateFormat.format(date);

        int timeYear=Integer.parseInt(sim.substring(0,4));

        int timeMonth=Integer.parseInt(sim.substring(4,6));

        int timeDay=Integer.parseInt(sim.substring(6,8));

        int timeHour=Integer.parseInt(sim.substring(8,10));

        int timeMinute=Integer.parseInt(sim.substring(10,12));

    }

自用笔记

你可能感兴趣的:(Android代码块总结,android)