美文网首页
自定义Chronometer解决app切到后台Chronomet

自定义Chronometer解决app切到后台Chronomet

作者: 阡陌昏晨 | 来源:发表于2022-08-09 17:02 被阅读0次

问题
当APP切到后台时候,再切回来时候,发现时间还是切出去时候的时间,这是为什么呢?
原来:
当APP进入后台时,会调用onWindowVisibilityChanged()方法,Chronometer回调的onChronometer方法是通过dispatchChronometerTick()方法进行回调的,但是在updateRunning()方法中有一个running变量,这个变量进行了一个是否在显示在前台判断,所以在后台时并不会调用dispatchChronometerTick()方法

image.png

解决方法自定义Chronometer

package com.cias.vas.lib.widget.tv;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import org.jetbrains.annotations.NotNull;

import java.util.Formatter;
import java.util.IllegalFormatException;
import java.util.Locale;

/**
 * @Description:
 * @Author: zhoudequn
 * @CreateDate: 2022/5/16 15:12
 */
public class MyChronometer extends AppCompatTextView {

    public interface OnChronometerTickListener {
        void onChronometerTick(MyChronometer myChronometer);
    }

    private long mBase;
    private boolean mVisible;
    private boolean mStarted;
    private boolean mRunning;
    private boolean mLogged;
    private String mFormat;
    private Formatter mFormatter;
    private Locale mFormatterLocale;
    private Object[] mFormatterArgs = new Object[1];
    private StringBuilder mFormatBuilder;
    private OnChronometerTickListener mOnChronometerTickListener;
    private StringBuilder mRecycle = new StringBuilder(8);

    private static final int TICK_WHAT = 2;

    public MyChronometer(@NonNull @NotNull Context context) {
        super(context);
    }

    public MyChronometer(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyChronometer(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mBase = SystemClock.elapsedRealtime();
        updateText(mBase);
    }

    public void setBase(long base) {
        mBase = base;
        dispatchChronometerTick();
        updateText(SystemClock.elapsedRealtime());
    }

    public long getBase() {
        return mBase;
    }

    public void setFormat(String format) {
        mFormat = format;
        if (format != null && mFormatBuilder == null) {
            mFormatBuilder = new StringBuilder(format.length() * 2);
        }
    }

    public String getFormat() {
        return mFormat;
    }

    public void setOnChronometerTickListener(OnChronometerTickListener listener) {
        mOnChronometerTickListener = listener;
    }

    public OnChronometerTickListener getOnChronometerTickListener() {
        return mOnChronometerTickListener;
    }

    public void start() {
        mStarted = true;
        updateRunning();
    }

    public void stop() {
        mStarted = false;
        updateRunning();
    }

    public void setStarted(boolean started) {
        mStarted = started;
        updateRunning();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mVisible = false;
        updateRunning();
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        updateRunning();
    }

    private synchronized void updateText(long now) {
        long seconds = now - mBase;
        seconds /= 1000;
        String text = DateUtils.formatElapsedTime(mRecycle, seconds);
        if (mFormat != null) {
            Locale loc = Locale.getDefault();
            if (mFormatter == null || !loc.equals(mFormatterLocale)) {
                mFormatterLocale = loc;
                mFormatter = new Formatter(mFormatBuilder, loc);
            }
            mFormatBuilder.setLength(0);
            mFormatterArgs[0] = text;
            try {
                mFormatter.format(mFormat, mFormatterArgs);
                text = mFormatBuilder.toString();
            } catch (IllegalFormatException ex) {
                if (!mLogged) {
                    mLogged = true;
                }
            }
        }
        setText(text);
    }

    private void updateRunning() {
        boolean running = mStarted;
        if (running != mRunning) {
            if (running) {
                updateText(SystemClock.elapsedRealtime());
                dispatchChronometerTick();
                mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), 1000);
            } else {
                mHandler.removeMessages(TICK_WHAT);
            }
            mRunning = running;
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message m) {
            if (mRunning) {
                updateText(SystemClock.elapsedRealtime());
                dispatchChronometerTick();
                sendMessageDelayed(Message.obtain(this, TICK_WHAT), 1000);
            }
        }
    };

    void dispatchChronometerTick() {
        if (mOnChronometerTickListener != null) {
            mOnChronometerTickListener.onChronometerTick(this);
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(MyChronometer.class.getName());
    }

    @SuppressLint("NewApi")
    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(MyChronometer.class.getName());
    }
}

相关文章

  • 自定义Chronometer解决app切到后台Chronomet

    问题当APP切到后台时候,再切回来时候,发现时间还是切出去时候的时间,这是为什么呢?原来:当APP进入后台时,会调...

  • 如何判断App切到后台

    Q:如何判断App被切到了后台(比如按Home键)。A:可以通过任务栈中顶部Activity的包名来判断,和App...

  • iOS 经验笔记

    1、 CABasicAnimation 按home键切到后台之后,再按home键回来动画就停止了 解决办法: 2、...

  • iOS后台保活App并持续接收消息探究

    在应用切到后台后,还想保持代码工作状态,有如下三种方案: 一、后台播放音频 后台播放一段无声音乐的方式,可使App...

  • 环信ios后台接收不到消息

    按官方文档配置,但是App切到后台3分钟以上,就收不到信息了 原因: 环信后台--上传ios证书 证书名称和上传的...

  • Android8.0 启动后台Service

    在一加手机上,用户升级了新版8.0的系统,用户将app切到后台,过一会儿就弹出“xxx app 已停止运行”的弹窗...

  • Android app被系统kill的场景

    何时发生 当我们的app被切到后台的时候,比如用户按下了home键或者切换到了别的应用,总之是我们的app不再和用...

  • App页面切换保护(适用金融类app)

    当用户使用完app后,一般都会自然切到后台,并不会主动去Kill掉app.这种情况下,如果app刚好停留在敏感数据...

  • iOS wkwebview 出现空白页面

    通过webview 开发的页面, 在app 进入后台后过段时间在切到前台时会出现web 页面白屏。出现问题的原因:...

  • Android从后台切到前台

    2019年7月30日 星期二 要用Application启动Activity才能切到前台,用Activity启动则...

网友评论

      本文标题:自定义Chronometer解决app切到后台Chronomet

      本文链接:https://www.haomeiwen.com/subject/xdvnwrtx.html