时间更新——TimeObserveView

实现每分钟更新一下时间

TimeObserveView

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import com.zdy.tv.utils.TimeUtils;

public class TimeObserveView extends android.support.v7.widget.AppCompatTextView {

    private BroadcastReceiver timeTickReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            refreshTime();
        }
    };

    public TimeObserveView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        refreshTime();
    }

    private void refreshTime() {
        setText(TimeUtils.getTodayTime());
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        IntentFilter filter = new IntentFilter();
        //代码核心
        filter.addAction(Intent.ACTION_TIME_TICK);
        getContext().registerReceiver(timeTickReceiver, filter);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getContext().unregisterReceiver(timeTickReceiver);
    }
}

TimeObserveView 使用


总结

    其实只要使用好ACTION_TIME_TICK,就能很容易实现每分钟刷新一下时间,至此又了解了一个新知识。

你可能感兴趣的:(时间更新——TimeObserveView)