实现每分钟更新一下时间
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 使用
<com.zdy.tv.ui.next.view.TimeObserveView
android:id="@+id/tv_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="68dp"
android:layout_marginTop="40dp"
android:textColor="#adb0b4"
android:textSize="18sp"
tools:text="05月04日 周四" />
总结
其实只要使用好ACTION_TIME_TICK,就能很容易实现每分钟刷新一下时间,至此又了解了一个新知识。