android.os.CountDownTimer

Here are the examples of the java api android.os.CountDownTimer taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

193 Examples 7

19 Source : DownTimer.java
with Apache License 2.0
from zuoweitan

public clreplaced DownTimer {

    private final String TAG = DownTimer.clreplaced.getSimpleName();

    private CountDownTimer mCountDownTimer;

    private DownTimerListener listener;

    /**
     * [开始倒计时功能]<BR>
     * [倒计为time长的时间,时间间隔为每秒]
     * @param time
     */
    public void startDown(long time) {
        startDown(time, 1000);
    }

    /**
     * [倒计为time长的时间,时间间隔为mills]
     * @param time
     * @param mills
     */
    public void startDown(long time, long mills) {
        mCountDownTimer = new CountDownTimer(time, mills) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (listener != null) {
                    listener.onTick(millisUntilFinished);
                } else {
                    NLog.e(TAG, "DownTimerListener can not be null");
                }
            }

            @Override
            public void onFinish() {
                if (listener != null) {
                    listener.onFinish();
                } else {
                    NLog.e(TAG, "DownTimerListener can not be null");
                }
                if (mCountDownTimer != null)
                    mCountDownTimer.cancel();
            }
        }.start();
    }

    /**
     * [停止倒计时功能]<BR>
     */
    public void stopDown() {
        if (mCountDownTimer != null)
            mCountDownTimer.cancel();
    }

    /**
     * [设置倒计时监听]<BR>
     * @param listener
     */
    public void setListener(DownTimerListener listener) {
        this.listener = listener;
    }
}

19 Source : SplashDelegate.java
with Apache License 2.0
from zion223

public clreplaced SplashDelegate extends NeteaseDelegate {

    private CountDownTimer countDownTimer;

    @Override
    public Object setLayout() {
        return R.layout.delegate_splash;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ScreenUtils.setStatusBarColor(getProxyActivity(), Color.parseColor("#Db2C1F"));
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View view) throws Exception {
        startCountDownTime();
    }

    private void startCountDownTime() {
        countDownTimer = new CountDownTimer(2000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                String authToken = SharePreferenceUtil.getInstance(getContext()).getAuthToken("");
                if (TextUtils.isEmpty(authToken)) {
                    getSupportDelegate().startWithPop(new LoginDelegate());
                } else {
                    getSupportDelegate().startWithPop(new BaseDelegate());
                }
            }
        };
        countDownTimer.start();
    }
}

19 Source : CountDownButton.java
with Apache License 2.0
from xuexiangjys

/**
 * 倒计时按钮
 *
 * @author xuexiang
 * @since 2019/1/14 下午10:10
 */
public clreplaced CountDownButton extends AppCompatButton {

    /**
     * 默认时间间隔1000ms
     */
    private static final int DEFAULT_INTERVAL = 1000;

    /**
     * 默认时长60s
     */
    private static final int DEFAULT_COUNTDOWN_TIME = 60 * 1000;

    /**
     * 默认倒计时文字格式(显示秒数)
     */
    private static final String DEFAULT_COUNT_FORMAT = "%ds";

    /**
     * 默认按钮文字 {@link #getText()}
     */
    private String mDefaultText;

    /**
     * 倒计时时长,单位为毫秒
     */
    private long mCountDownTime;

    /**
     * 时间间隔,单位为毫秒
     */
    private long mInterval;

    /**
     * 倒计时文字格式
     */
    private String mCountDownFormat;

    /**
     * 倒计时是否可用
     */
    private boolean mEnableCountDown = true;

    /**
     * 点击事件监听器
     */
    private OnClickListener mOnClickListener;

    /**
     * 倒计时
     */
    private CountDownTimer mCountDownTimer;

    /**
     * 是否正在执行倒计时
     */
    private boolean isCountDownNow;

    public CountDownButton(Context context) {
        this(context, null);
    }

    public CountDownButton(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.CountDownButtonStyle);
    }

    public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        // 获取自定义属性值
        initAttr(context, attrs, defStyleAttr);
        // 初始化倒计时Timer
        if (mCountDownTimer == null) {
            mCountDownTimer = new CountDownTimer(mCountDownTime, mInterval) {

                @Override
                public void onTick(long millisUntilFinished) {
                    setText(String.format(Locale.CHINA, mCountDownFormat, millisUntilFinished / 1000));
                }

                @Override
                public void onFinish() {
                    isCountDownNow = false;
                    setEnabled(true);
                    setText(mDefaultText);
                }
            };
        }
    }

    /**
     * 获取自定义属性值
     *
     * @param context
     * @param attrs
     */
    private void initAttr(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CountDownButton, defStyleAttr, 0);
        mCountDownFormat = typedArray.getString(R.styleable.CountDownButton_cdbt_countDownFormat);
        if (TextUtils.isEmpty(mCountDownFormat)) {
            mCountDownFormat = DEFAULT_COUNT_FORMAT;
        }
        mCountDownTime = typedArray.getInteger(R.styleable.CountDownButton_cdbt_countDown, DEFAULT_COUNTDOWN_TIME);
        mInterval = typedArray.getInteger(R.styleable.CountDownButton_cdbt_countDownInterval, DEFAULT_INTERVAL);
        mEnableCountDown = (mCountDownTime > mInterval) && typedArray.getBoolean(R.styleable.CountDownButton_cdbt_enableCountDown, true);
        typedArray.recycle();
    }

    @Override
    public void setOnClickListener(OnClickListener onClickListener) {
        super.setOnClickListener(onClickListener);
        mOnClickListener = onClickListener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_UP:
                Rect rect = new Rect();
                getGlobalVisibleRect(rect);
                if (mOnClickListener != null && rect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    mOnClickListener.onClick(this);
                }
                if (mEnableCountDown && rect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    startCountDown();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 开始计算
     */
    private void startCountDown() {
        mDefaultText = getText().toString();
        // 设置按钮不可点击
        setEnabled(false);
        // 开始倒计时
        mCountDownTimer.start();
        isCountDownNow = true;
    }

    public CountDownButton setEnableCountDown(boolean enableCountDown) {
        mEnableCountDown = (mCountDownTime > mInterval) && enableCountDown;
        return this;
    }

    public CountDownButton setCountDownFormat(String countDownFormat) {
        mCountDownFormat = countDownFormat;
        return this;
    }

    public CountDownButton setCountDownTime(long countDownTime) {
        mCountDownTime = countDownTime;
        return this;
    }

    public CountDownButton setInterval(long interval) {
        mInterval = interval;
        return this;
    }

    /**
     * 是否正在执行倒计时
     *
     * @return 倒计时期间返回true否则返回false
     */
    public boolean isCountDownNow() {
        return isCountDownNow;
    }

    /**
     * 设置倒计时数据
     *
     * @param count           时长
     * @param interval        间隔
     * @param countDownFormat 文字格式
     */
    public CountDownButton setCountDown(long count, long interval, String countDownFormat) {
        mCountDownTime = count;
        mCountDownFormat = countDownFormat;
        mInterval = interval;
        setEnableCountDown(true);
        return this;
    }

    /**
     * 取消倒计时
     */
    public void cancelCountDown() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        isCountDownNow = false;
        setText(mDefaultText);
        setEnabled(true);
    }

    @Override
    public void setEnabled(boolean enabled) {
        if (isCountDownNow()) {
            return;
        }
        super.setEnabled(enabled);
        setClickable(enabled);
    }
}

19 Source : CountDownButtonHelper.java
with Apache License 2.0
from xuexiangjys

/**
 * 倒计时Button帮助类
 *
 * @author xuexiang
 * @since 2018/11/22 上午12:38
 */
public clreplaced CountDownButtonHelper {

    /**
     * 倒计时timer
     */
    private CountDownTimer mCountDownTimer;

    private OnCountDownListener mListener;

    private TextView mButton;

    /**
     * 倒计时总时间
     */
    private int mCountDownTime;

    /**
     * 倒计时间期
     */
    private int mInterval;

    /**
     * 构造方法
     * @param button        需要显示倒计时的Button
     * @param countDownTime 倒计时总时间,单位是秒
     */
    public CountDownButtonHelper(TextView button, int countDownTime) {
        this(button, countDownTime, 1);
    }

    /**
     * 构造方法
     * @param button        需要显示倒计时的Button
     * @param countDownTime 需要进行倒计时的最大值,单位是秒
     * @param interval      倒计时的间隔,单位是秒
     */
    public CountDownButtonHelper(TextView button, int countDownTime, int interval) {
        mButton = button;
        mCountDownTime = countDownTime;
        mInterval = interval;
        initCountDownTimer();
    }

    /**
     * 初始化倒计时器
     */
    private void initCountDownTimer() {
        // 由于CountDownTimer并不是准确计时,在onTick方法调用的时候,time会有1-10ms左右的误差,这会导致最后一秒不会调用onTick()
        // 因此,设置间隔的时候,默认减去了10ms,从而减去误差。
        // 经过以上的微调,最后一秒的显示时间会由于10ms延迟的积累,导致显示时间比1s长max*10ms的时间,其他时间的显示正常,总时间正常
        if (mCountDownTimer == null) {
            mCountDownTimer = new CountDownTimer(mCountDownTime * 1000, mInterval * 1000 - 10) {

                @Override
                public void onTick(long time) {
                    // 第一次调用会有1-10ms的误差,因此需要+15ms,防止第一个数不显示,第二个数显示2s
                    int surplusTime = (int) ((time + 15) / 1000);
                    if (mListener != null) {
                        mListener.onCountDown(surplusTime);
                    } else {
                        mButton.setText(surplusTime + "s");
                    }
                }

                @Override
                public void onFinish() {
                    mButton.setEnabled(true);
                    if (mListener != null) {
                        mListener.onFinished();
                    } else {
                        mButton.setText(mButton.getResources().getString(R.string.xui_count_down_finish));
                    }
                }
            };
        }
    }

    /**
     * 开始倒计时
     */
    public void start() {
        initCountDownTimer();
        mButton.setEnabled(false);
        mCountDownTimer.start();
    }

    /**
     * 设置倒计时的监听器
     *
     * @param listener
     */
    public CountDownButtonHelper setOnCountDownListener(OnCountDownListener listener) {
        mListener = listener;
        return this;
    }

    /**
     * 计时时监听接口
     *
     * @author xx
     */
    public interface OnCountDownListener {

        /**
         * 正在倒计时
         * @param time 剩余的时间
         */
        void onCountDown(int time);

        /**
         * 倒计时结束
         */
        void onFinished();
    }

    /**
     * 取消倒计时
     */
    public void cancel() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    /**
     * 资源回收
     */
    public void recycle() {
        cancel();
        mListener = null;
        mButton = null;
    }
}

19 Source : CountDownButton.java
with Apache License 2.0
from xiaohaibin

/**
 * link https://xiaohaibin.github.io/
 * email: [email protected]
 * github: https://github.com/xiaohaibin
 * descibe 短信验证码倒计时button
 */
@SuppressLint("AppCompatCustomView")
public clreplaced CountDownButton extends TextView {

    private long time = 60 * 1000;

    private String beforeText = "获取验证码";

    private String afterText = "重新获取";

    private CountDownTimer timer;

    public CountDownButton(Context context) {
        super(context);
        initView();
    }

    public CountDownButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public CountDownButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    /**
     * 初始化操作
     */
    private void initView() {
        if (!TextUtils.isEmpty(getText())) {
            beforeText = getText().toString().trim();
        }
        setText(beforeText);
        initTimer();
    }

    /**
     * 开始倒计时
     */
    public void start() {
        timer.start();
        setText(String.valueOf(time / 1000 + "S后重试"));
    }

    /**
     * 清除倒计时
     */
    private void clearTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        clearTimer();
        super.onDetachedFromWindow();
    }

    private void initTimer() {
        if (timer == null) {
            timer = new CountDownTimer(time, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    setEnabled(false);
                    setText(String.valueOf(millisUntilFinished / 1000 + "秒后重发"));
                }

                @Override
                public void onFinish() {
                    setEnabled(true);
                    setText(afterText);
                }
            };
        }
    }
}

19 Source : CountDownButton.java
with MIT License
from WhiteDG

/**
 * Author: Wh1te
 * Date: 2016/10/18
 */
public clreplaced CountDownButton extends Button {

    /**
     * 默认时间间隔1000ms
     */
    private static final long DEFAULT_INTERVAL = 1000;

    /**
     * 默认时长60s
     */
    private static final long DEFAULT_COUNT = 60 * 1000;

    /**
     * 默认倒计时文字格式(显示秒数)
     */
    private static final String DEFAULT_COUNT_FORMAT = "%d";

    /**
     * 倒计时结束后按钮显示的文本
     */
    private String mCdFinishText;

    /**
     * 倒计时时长,单位为毫秒
     */
    private long mCount;

    /**
     * 时间间隔,单位为毫秒
     */
    private long mInterval;

    /**
     * 倒计时文字格式
     */
    private String mCountDownFormat = DEFAULT_COUNT_FORMAT;

    /**
     * 倒计时是否可用
     */
    private boolean mEnableCountDown = true;

    /**
     * 点击事件监听器
     */
    private OnClickListener onClickListener;

    /**
     * 倒计时
     */
    private CountDownTimer mCountDownTimer;

    /**
     * 是否正在执行倒计时
     */
    private boolean isCountDownNow;

    public CountDownButton(Context context) {
        super(context);
    }

    public CountDownButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        // 获取自定义属性值
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CountDownButton);
        mCountDownFormat = typedArray.getString(R.styleable.CountDownButton_countDownFormat);
        mCdFinishText = typedArray.getString(R.styleable.CountDownButton_cdFinishText);
        if (typedArray.hasValue(R.styleable.CountDownButton_countDown)) {
            mCount = (int) typedArray.getFloat(R.styleable.CountDownButton_countDown, DEFAULT_COUNT);
        }
        mInterval = (int) typedArray.getFloat(R.styleable.CountDownButton_countDownInterval, DEFAULT_INTERVAL);
        mEnableCountDown = (mCount > mInterval) && typedArray.getBoolean(R.styleable.CountDownButton_enableCountDown, true);
        typedArray.recycle();
        // 初始化倒计时Timer
        if (mCountDownTimer == null) {
            mCountDownTimer = new CountDownTimer(mCount, mInterval) {

                @Override
                public void onTick(long millisUntilFinished) {
                    setText(String.format(Locale.CHINA, mCountDownFormat, millisUntilFinished / 1000));
                }

                @Override
                public void onFinish() {
                    isCountDownNow = false;
                    setEnabled(true);
                    setText(TextUtils.isEmpty(mCdFinishText) ? getText().toString() : mCdFinishText);
                }
            };
        }
    }

    @Override
    public void setOnClickListener(OnClickListener onClickListener) {
        super.setOnClickListener(onClickListener);
        this.onClickListener = onClickListener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_UP:
                Rect rect = new Rect();
                this.getGlobalVisibleRect(rect);
                if (onClickListener != null && rect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    onClickListener.onClick(this);
                }
                if (mEnableCountDown && rect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    // 设置按钮不可点击
                    setEnabled(false);
                    // 开始倒计时
                    mCountDownTimer.start();
                    isCountDownNow = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    public void setEnableCountDown(boolean enableCountDown) {
        this.mEnableCountDown = (mCount > mInterval) && enableCountDown;
    }

    public void setCountDownFormat(String countDownFormat) {
        this.mCountDownFormat = countDownFormat;
    }

    public void setCount(long count) {
        this.mCount = count;
    }

    public void setInterval(long interval) {
        mInterval = interval;
    }

    /**
     * 是否正在执行倒计时
     *
     * @return 倒计时期间返回true否则返回false
     */
    public boolean isCountDownNow() {
        return isCountDownNow;
    }

    /**
     * 设置倒计时数据
     *
     * @param count           时长
     * @param interval        间隔
     * @param countDownFormat 文字格式
     */
    public void setCountDown(long count, long interval, String countDownFormat) {
        this.mCount = count;
        this.mCountDownFormat = countDownFormat;
        this.mInterval = interval;
        setEnableCountDown(true);
    }

    public void setCDFinishText(String cdFinishText) {
        this.mCdFinishText = cdFinishText;
    }

    /**
     * 移除倒计时
     */
    public void removeCountDown() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        isCountDownNow = false;
        setText(TextUtils.isEmpty(mCdFinishText) ? getText().toString() : mCdFinishText);
        setEnabled(true);
    }

    @Override
    public void setEnabled(boolean enabled) {
        if (isCountDownNow()) {
            return;
        }
        super.setEnabled(enabled);
        setClickable(enabled);
    }

    @Override
    protected void onDetachedFromWindow() {
        removeCountDown();
        super.onDetachedFromWindow();
    }
}

19 Source : PauseReceiver.java
with GNU General Public License v3.0
from wesaphzt

public clreplaced PauseReceiver extends BroadcastReceiver {

    public static CountDownTimer mCountdown;

    public static boolean isRunning = false;

    @Override
    public void onReceive(final Context context, Intent intent) {
        String action = intent.getStringExtra("pause_service");
        if (action.equals("pause_service_time")) {
            // close notification tray
            Intent i = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            context.sendBroadcast(i);
            if (disabled) {
                Toast.makeText(context, "Service is already paused", Toast.LENGTH_SHORT).show();
                return;
            } else {
                disabled = true;
                LockWidgetProvider lockWidgetProvider = new LockWidgetProvider();
                lockWidgetProvider.setWidgetPause(context);
            }
            // shared prefs
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            int pauseMinuteTime = Integer.parseInt(prefs.getString("PAUSE_TIME", String.valueOf(1)));
            int milliPauseTime = pauseMinuteTime * 60 * 1000;
            String plural;
            if (pauseMinuteTime == 1) {
                plural = "minute";
            } else {
                plural = "minutes";
            }
            Toast.makeText(context, "Service paused for " + pauseMinuteTime + " " + plural, Toast.LENGTH_LONG).show();
            mCountdown = new CountDownTimer(milliPauseTime, 1000) {

                public void onTick(long millisUntilFinished) {
                    isRunning = true;
                }

                public void onFinish() {
                    // prevent lock animation artifacts
                    mInitialized = false;
                    // init
                    disabled = false;
                    isRunning = false;
                    LockWidgetProvider lockWidgetProvider = new LockWidgetProvider();
                    lockWidgetProvider.setWidgetStart(context);
                    Toast.makeText(context, "Service resumed", Toast.LENGTH_LONG).show();
                }
            }.start();
        }
    }
}

19 Source : MainActivity.java
with Apache License 2.0
from velmurugan35

public clreplaced MainActivity extends Activity implements OnClickListener {

    private CountDownTimer countDownTimer;

    private boolean timerHreplacedtarted = false;

    private Button startB;

    public TextView text;

    private final long startTime = 30 * 1000;

    private final long interval = 1 * 1000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startB = (Button) this.findViewById(R.id.button);
        startB.setOnClickListener(this);
        text = (TextView) this.findViewById(R.id.timer);
        countDownTimer = new MyCountDownTimer(startTime, interval);
        text.setText(text.getText() + String.valueOf(startTime / 1000));
    }

    public clreplaced MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }

        @Override
        public void onFinish() {
            text.setText("Time's up!");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            text.setText("" + millisUntilFinished / 1000);
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (!timerHreplacedtarted) {
            countDownTimer.start();
            timerHreplacedtarted = true;
            startB.setText("STOP");
        } else {
            countDownTimer.cancel();
            timerHreplacedtarted = false;
            startB.setText("RESTART");
        }
    }
}

19 Source : LoginWithPhonePresenter.java
with MIT License
from TuyaInc

/**
 * Created by letian on 15/5/30.
 */
public clreplaced LoginWithPhonePresenter extends BasePresenter {

    private static final String TAG = "LoginWithPhonePresenter";

    protected Activity mContext;

    private static final int GET_VALIDATE_CODE_PERIOD = 60 * 1000;

    protected ILoginWithPhoneView mView;

    private CountDownTimer mCountDownTimer;

    private boolean isCountDown;

    protected String mPhoneCode;

    private String mCountryName;

    protected boolean mSend;

    public LoginWithPhonePresenter(Context context, ILoginWithPhoneView view) {
        super();
        mContext = (Activity) context;
        mView = view;
        getCountry();
    }

    private void getCountry() {
        String countryKey = CountryUtils.getCountryKey(TuyaSdk.getApplication());
        if (!TextUtils.isEmpty(countryKey)) {
            mCountryName = CountryUtils.getCountryreplacedle(countryKey);
            mPhoneCode = CountryUtils.getCountryNum(countryKey);
        } else {
            countryKey = CountryUtils.getCountryDefault(TuyaSdk.getApplication());
            mCountryName = CountryUtils.getCountryreplacedle(countryKey);
            mPhoneCode = CountryUtils.getCountryNum(countryKey);
        }
        mView.setCountry(mCountryName, mPhoneCode);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case 0x01:
                if (resultCode == Activity.RESULT_OK) {
                    mCountryName = data.getStringExtra(CountryListActivity.COUNTRY_NAME);
                    mPhoneCode = data.getStringExtra(CountryListActivity.PHONE_CODE);
                    mView.setCountry(mCountryName, mPhoneCode);
                }
                break;
        }
    }

    public static final int MSG_SEND_VALIDATE_CODE_SUCCESS = 12;

    public static final int MSG_SEND_VALIDATE_CODE_ERROR = 13;

    public static final int MSG_LOGIN_SUCCESS = 15;

    public static final int MSG_LOGIN_ERROR = 16;

    /**
     * 获取验证码
     *
     * @return
     */
    public void getValidateCode() {
        mSend = true;
        TuyaHomeSdk.getUserInstance().getValidateCode(mPhoneCode, mView.getPhone(), new IValidateCallback() {

            @Override
            public void onSuccess() {
                mHandler.sendEmptyMessage(MSG_SEND_VALIDATE_CODE_SUCCESS);
            }

            @Override
            public void onError(String s, String s1) {
                getValidateCodeFail(s, s1);
            }
        });
    }

    protected void getValidateCodeFail(String errorCode, String errorMsg) {
        Message msg = MessageUtil.getCallFailMessage(MSG_SEND_VALIDATE_CODE_ERROR, errorCode, errorMsg);
        mHandler.sendMessage(msg);
        mSend = false;
    }

    /**
     * 登录
     *
     * @return
     */
    public void login() {
        String phoneNumber = mView.getPhone();
        String code = mView.getValidateCode();
        TuyaHomeSdk.getUserInstance().loginWithPhone(mPhoneCode, phoneNumber, code, new ILoginCallback() {

            @Override
            public void onSuccess(User user) {
                mHandler.sendEmptyMessage(MSG_LOGIN_SUCCESS);
            }

            @Override
            public void onError(String s, String s1) {
                Message msg = MessageUtil.getCallFailMessage(MSG_LOGIN_ERROR, s, s1);
                mHandler.sendMessage(msg);
            }
        });
    }

    public void selectCountry() {
        mContext.startActivityForResult(new Intent(mContext, CountryListActivity.clreplaced), 0x01);
    }

    /**
     * 构造倒计时
     */
    private void buildCountDown() {
        mCountDownTimer = new Countdown(GET_VALIDATE_CODE_PERIOD, 1000);
        mCountDownTimer.start();
        mView.disableGetValidateCode();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch(msg.what) {
            case MSG_SEND_VALIDATE_CODE_SUCCESS:
                buildCountDown();
                mView.modelResult(msg.what, null);
                break;
            case MSG_SEND_VALIDATE_CODE_ERROR:
                mView.modelResult(msg.what, (Result) msg.obj);
                break;
            case MSG_LOGIN_ERROR:
                mView.modelResult(msg.what, (Result) msg.obj);
                break;
            case MSG_LOGIN_SUCCESS:
                mView.modelResult(msg.what, null);
                loginSuccess();
                break;
        }
        return super.handleMessage(msg);
    }

    private void loginSuccess() {
        Constant.finishActivity();
        LoginHelper.afterLogin();
        ActivityUtils.gotoHomeActivity(mContext);
    }

    @Override
    public void onDestroy() {
        mCountDownTimer = null;
    }

    public void validateBtResume() {
        if (mCountDownTimer != null) {
            mCountDownTimer.onFinish();
        }
    }

    public boolean isSended() {
        return mSend;
    }

    private clreplaced Countdown extends CountDownTimer {

        public Countdown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mView.setCountdown((int) (millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            mView.enableGetValidateCode();
            mSend = false;
            mView.checkValidateCode();
        }
    }
}

19 Source : Reg.java
with Apache License 2.0
from stytooldex

/**
 * 注册验证码计时服务
 * @author talentClreplaced
 */
public clreplaced Reg extends Service {

    public static final String IN_RUNNING = "nico.styTool.IN_RUNNING";

    public static final String END_RUNNING = "nico.styTool.END_RUNNING";

    private static Handler mHandler;

    private static CountDownTimer mCodeTimer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 第一个参数是总时间, 第二个参数是间隔
        mCodeTimer = new CountDownTimer(129000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                // 广播剩余时间
                broadcastUpdate(IN_RUNNING, millisUntilFinished / 1000 + "");
            }

            @Override
            public void onFinish() {
                // 广播倒计时结束
                broadcastUpdate(END_RUNNING);
                // 停止服务
                stopSelf();
            }
        };
        // 开始倒计时
        mCodeTimer.start();
        return super.onStartCommand(intent, flags, startId);
    }

    // 发送广播
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    // 发送带有数据的广播
    private void broadcastUpdate(final String action, String time) {
        final Intent intent = new Intent(action);
        intent.putExtra("time", time);
        sendBroadcast(intent);
    }
}

19 Source : msf_shell.java
with Apache License 2.0
from stytooldex

/**
 * 注册验证码计时服务
 * @author talentClreplaced
 */
public clreplaced msf_shell extends Service {

    public static final String IN_RUNNING = "nico.styTool.IN_RUNNING";

    public static final String END_RUNNING = "nico.styTool.END_RUNNING";

    private static Handler mHandler;

    private static CountDownTimer mCodeTimer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 第一个参数是总时间, 第二个参数是间隔
        mCodeTimer = new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                // 广播剩余时间
                broadcastUpdate(IN_RUNNING, millisUntilFinished / 1000 + "");
            }

            @Override
            public void onFinish() {
                // 广播倒计时结束
                broadcastUpdate(END_RUNNING);
                // 停止服务
                stopSelf();
            }
        };
        // 开始倒计时
        mCodeTimer.start();
        return super.onStartCommand(intent, flags, startId);
    }

    // 发送广播
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    // 发送带有数据的广播
    private void broadcastUpdate(final String action, String time) {
        final Intent intent = new Intent(action);
        intent.putExtra("time", time);
        sendBroadcast(intent);
    }
}

19 Source : TimerService.java
with GNU General Public License v3.0
from SecUSo

/**
 * Workout timer as a service.
 * Has two different timers for workout and rest functionality.
 * Can play sounds depending ot the current settings.
 * Can pause, resume, skip and go back to the pervious timer.
 *
 * @author Alexander Karakuz
 * @version 20170809
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
public clreplaced TimerService extends Service {

    // General
    private SharedPreferences settings;

    // Broadcast action identifier for the broadcasted service messages
    public static final String COUNTDOWN_BROADCAST = "org.secuso.privacyfriendlytraining.COUNTDOWN";

    public static final String NOTIFICATION_BROADCAST = "org.secuso.privacyfriendlytraining.NOTIFICATION";

    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();

    // Timer for the workout countdown
    private CountDownTimer workoutTimer = null;

    private CountDownTimer restTimer = null;

    // Sound
    MediaPlayer mediaPlayer = null;

    // Values for workout and rest time and sets to perform
    private long blockPeriodizationTime = 0;

    private int blockPeriodizationSets = 0;

    private long startTime = 0;

    private long workoutTime = 0;

    private long restTime = 0;

    private int sets = 0;

    // Values during the workout
    private long savedTime = 0;

    private int currentSet = 1;

    // Timer Flags
    private boolean isBlockPeriodization = false;

    private boolean isStarttimer = false;

    private boolean isWorkout = false;

    private boolean isPaused = false;

    private boolean isCancelAlert = false;

    // Broadcast string messages
    private String currentreplacedle = "";

    // Notification variables
    private static final int NOTIFICATION_ID = 1;

    private NotificationCompat.Builder notiBuilder = null;

    private NotificationManager notiManager = null;

    private boolean isAppInBackground = false;

    // Database for the statistics
    private PFASQLiteHelper database = null;

    private WorkoutSessionData statistics = null;

    private int timeSpentWorkingOut = 0;

    private int caloriesBurned = 0;

    private int caloriesPerExercise = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        this.restTimer = createRestTimer(this.startTime);
        this.workoutTimer = createWorkoutTimer(this.workoutTime);
        this.settings = PreferenceManager.getDefaultSharedPreferences(this);
        registerReceiver(notificationReceiver, new IntentFilter(NOTIFICATION_BROADCAST));
        notiBuilder = new NotificationCompat.Builder(this);
        notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private final BroadcastReceiver notificationReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (!currentreplacedle.equals(getString(R.string.workout_headline_done)) && !isCancelAlert) {
                if (isPaused) {
                    resumeTimer();
                    int secondsUntilFinished = (int) Math.ceil(savedTime / 1000.0);
                    updateNotification(secondsUntilFinished);
                } else {
                    pauseTimer();
                }
            }
        }
    };

    public clreplaced LocalBinder extends Binder {

        public TimerService getService() {
            return TimerService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onDestroy() {
        if (workoutTimer != null) {
            workoutTimer.cancel();
        }
        if (restTimer != null) {
            restTimer.cancel();
        }
        saveStatistics();
        unregisterReceiver(notificationReceiver);
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * Creates the workout timer.
     * Broadcasts the current millis on every tick.
     * Broadcasts the seconds left on every second.
     * Starts the rest timer if there are sets left to perform.
     *
     * Maybe Strategy Pattern for the onFinish() if another Timer would be introduce.
     * Tick has to be 10ms for the progress bar to animate fluently.
     *
     * @param duration Duration of the workout timer
     * @return CountDownTimer
     */
    private CountDownTimer createWorkoutTimer(final long duration) {
        return new CountDownTimer(duration, 10) {

            int lastBroadcastedSecond = (int) Math.ceil(duration / 1000.0);

            /**
             * Broadcasts the current milis on every tick and the current seconds every second
             *
             * @param millisUntilFinished
             */
            @Override
            public void onTick(long millisUntilFinished) {
                int secondsUntilFinished = (int) Math.ceil(millisUntilFinished / 1000.0);
                savedTime = millisUntilFinished;
                Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("onTickMillis", millisUntilFinished);
                if (// send and play sound only every minute
                lastBroadcastedSecond > secondsUntilFinished) {
                    broadcast.putExtra("timer_replacedle", currentreplacedle).putExtra("countdown_seconds", secondsUntilFinished);
                    lastBroadcastedSecond = secondsUntilFinished;
                    playSound(secondsUntilFinished, true);
                    updateNotification(secondsUntilFinished);
                    timeSpentWorkingOut += 1;
                }
                sendBroadcast(broadcast);
            }

            /**
             * Calculates the calories burned during the workout and adds them to global variable.
             * Starts the rest timer if there are sets left to perform. Othterwise boradcasts
             * that the workout tis over and how much calories were burned overall.
             */
            @Override
            public void onFinish() {
                Intent broadcast = new Intent(COUNTDOWN_BROADCAST);
                caloriesBurned += caloriesPerExercise;
                if (currentSet < sets) {
                    if (isBlockPeriodization && currentSet % blockPeriodizationSets == 0) {
                        currentreplacedle = getResources().getString(R.string.workout_block_periodization_headline);
                        broadcast.putExtra("timer_replacedle", currentreplacedle).putExtra("countdown_seconds", (int) blockPeriodizationTime / 1000).putExtra("new_timer", blockPeriodizationTime);
                        restTimer = createRestTimer(blockPeriodizationTime);
                    } else {
                        currentreplacedle = getResources().getString(R.string.workout_headline_rest);
                        broadcast.putExtra("timer_replacedle", currentreplacedle).putExtra("countdown_seconds", (int) restTime / 1000).putExtra("new_timer", restTime);
                        restTimer = createRestTimer(restTime);
                    }
                    sendBroadcast(broadcast);
                    isWorkout = false;
                    timeSpentWorkingOut += 1;
                    restTimer.start();
                } else {
                    currentreplacedle = getResources().getString(R.string.workout_headline_done);
                    updateNotification(0);
                    broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("timer_replacedle", currentreplacedle).putExtra("workout_finished", true);
                    sendBroadcast(broadcast);
                    timeSpentWorkingOut += 1;
                }
            }
        };
    }

    /**
     * Creates the rest timer.
     * Broadcasts the current millis on every tick.
     * Broadcasts the seconds left on every second.
     * Starts the workout timer when finished.
     *
     * @param duration Duration of the rest timer.
     * @return CountDown Timer
     */
    private CountDownTimer createRestTimer(final long duration) {
        return new CountDownTimer(duration, 10) {

            int lastBroadcastedSecond = (int) Math.ceil(duration / 1000.0);

            /**
             * Broadcasts the current milis on every tick and the current seconds every second
             *
             * @param millisUntilFinished
             */
            @Override
            public void onTick(long millisUntilFinished) {
                int secondsUntilFinished = (int) Math.ceil(millisUntilFinished / 1000.0);
                savedTime = millisUntilFinished;
                Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("onTickMillis", millisUntilFinished);
                if (// send and play sound only every minute
                lastBroadcastedSecond > secondsUntilFinished) {
                    broadcast.putExtra("timer_replacedle", currentreplacedle).putExtra("countdown_seconds", secondsUntilFinished);
                    lastBroadcastedSecond = secondsUntilFinished;
                    playSound(secondsUntilFinished, false);
                    updateNotification(secondsUntilFinished);
                    timeSpentWorkingOut += 1;
                }
                sendBroadcast(broadcast);
            }

            /**
             * Starts the next workout timer and broadcasts it.
             */
            @Override
            public void onFinish() {
                Intent broadcast = new Intent(COUNTDOWN_BROADCAST);
                if (isStarttimer) {
                    isStarttimer = false;
                } else {
                    currentSet += 1;
                }
                currentreplacedle = getResources().getString(R.string.workout_headline_workout);
                broadcast.putExtra("timer_replacedle", currentreplacedle).putExtra("current_set", currentSet).putExtra("sets", sets).putExtra("countdown_seconds", (int) workoutTime / 1000).putExtra("new_timer", workoutTime);
                sendBroadcast(broadcast);
                isWorkout = true;
                workoutTimer = createWorkoutTimer(workoutTime);
                workoutTimer.start();
                timeSpentWorkingOut += 1;
            }
        };
    }

    /**
     * Initialize all timer and set values and start the workout routine.
     *
     * @param workoutTime Duration of each workout timer
     * @param restTime Duration of each rest timer
     * @param startTime Duration of the start timer
     * @param sets Amount of sets to be performed
     * @param isBlockPeriodization Flag if block periodization feature was enabled
     * @param blockPeriodizationTime Duration of the block periodization rest phase
     * @param blockPeriodizationSets Interval determining after how many sets a block rest occurs
     */
    public void startWorkout(long workoutTime, long restTime, long startTime, int sets, boolean isBlockPeriodization, long blockPeriodizationTime, int blockPeriodizationSets) {
        this.blockPeriodizationTime = blockPeriodizationTime * 1000;
        this.blockPeriodizationSets = blockPeriodizationSets;
        this.isBlockPeriodization = isBlockPeriodization;
        this.workoutTime = workoutTime * 1000;
        this.startTime = startTime * 1000;
        this.restTime = restTime * 1000;
        this.currentSet = 1;
        this.sets = sets;
        this.timeSpentWorkingOut = 0;
        this.caloriesBurned = 0;
        this.caloriesPerExercise = calculateUserCalories((float) workoutTime);
        this.workoutTimer = createWorkoutTimer(this.workoutTime);
        this.restTimer = createRestTimer(this.startTime);
        // Use rest timer as a start timer before the workout begins
        if (startTime != 0) {
            this.savedTime = this.restTime;
            this.currentreplacedle = getResources().getString(R.string.workout_headline_start_timer);
            isWorkout = false;
            isStarttimer = true;
            restTimer.start();
        } else {
            this.savedTime = this.workoutTime;
            this.currentreplacedle = getResources().getString(R.string.workout_headline_workout);
            isWorkout = true;
            this.workoutTimer.start();
        }
    }

    /**
     * Pause the currently working timer
     */
    public void pauseTimer() {
        if (isWorkout && workoutTimer != null) {
            this.workoutTimer.cancel();
        } else if (restTimer != null) {
            this.restTimer.cancel();
        }
        isPaused = true;
        updateNotification((int) Math.ceil(savedTime / 1000.0));
    }

    /**
     * Resume the currently working timer
     */
    public void resumeTimer() {
        if (isWorkout) {
            this.workoutTimer = createWorkoutTimer(savedTime);
            this.workoutTimer.start();
        } else {
            this.restTimer = createRestTimer(savedTime);
            this.restTimer.start();
        }
        int secondsUntilFinished = (int) Math.ceil(savedTime / 1000.0);
        Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("countdown_seconds", secondsUntilFinished);
        sendBroadcast(broadcast);
        isPaused = false;
    }

    /**
     * Switch to the next timer
     */
    public void nextTimer() {
        // If user is not in the final workout switch to rest phase
        if (isWorkout && currentSet < sets && restTime != 0) {
            this.workoutTimer.cancel();
            isWorkout = false;
            // Check if the next rest phase is normal or a block rest
            long time = (isBlockPeriodization && currentSet % blockPeriodizationSets == 0) ? this.blockPeriodizationTime : this.restTime;
            this.currentreplacedle = (isBlockPeriodization && currentSet % blockPeriodizationSets == 0) ? getResources().getString(R.string.workout_block_periodization_headline) : getResources().getString(R.string.workout_headline_rest);
            Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("timer_replacedle", currentreplacedle).putExtra("new_timer", time);
            if (isPaused) {
                this.savedTime = time;
            } else {
                restTimer = createRestTimer(time);
                restTimer.start();
            }
            sendBroadcast(broadcast);
        } else // If user is in the rest phase or the rest phase is 0 switch to the workout phase
        if (currentSet < sets) {
            this.restTimer.cancel();
            this.workoutTimer.cancel();
            isWorkout = true;
            this.currentreplacedle = getResources().getString(R.string.workout_headline_workout);
            // If rest timer was used as a start timer, ignore the first set increase
            if (isStarttimer) {
                this.isStarttimer = false;
            } else {
                this.currentSet += 1;
            }
            Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("timer_replacedle", currentreplacedle).putExtra("current_set", currentSet).putExtra("new_timer", workoutTime).putExtra("sets", sets);
            if (isPaused) {
                this.savedTime = workoutTime;
            } else {
                workoutTimer = createWorkoutTimer(workoutTime);
                workoutTimer.start();
            }
            sendBroadcast(broadcast);
        }
    }

    /**
     * Switch to the previous timer
     */
    public void prevTimer() {
        // If user is not in the first workout phase go back to the rest phase
        if (isWorkout && currentSet >= 2 && restTime != 0) {
            this.workoutTimer.cancel();
            isWorkout = false;
            this.currentSet -= 1;
            long time = (isBlockPeriodization && currentSet % blockPeriodizationSets == 0) ? this.blockPeriodizationTime : this.restTime;
            this.currentreplacedle = (isBlockPeriodization && currentSet % blockPeriodizationSets == 0) ? getResources().getString(R.string.workout_block_periodization_headline) : getResources().getString(R.string.workout_headline_rest);
            Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("timer_replacedle", currentreplacedle).putExtra("sets", sets).putExtra("new_timer", time).putExtra("current_set", currentSet);
            if (isPaused) {
                this.savedTime = time;
            } else {
                restTimer = createRestTimer(time);
                restTimer.start();
            }
            sendBroadcast(broadcast);
        } else // If user is in the first workout phase, just reset the timer
        if (isWorkout && currentSet == 1) {
            Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("new_timer", workoutTime);
            if (isPaused) {
                this.savedTime = workoutTime;
            } else {
                this.workoutTimer.cancel();
                workoutTimer = createWorkoutTimer(workoutTime);
                workoutTimer.start();
            }
            sendBroadcast(broadcast);
        } else // If user is in the rest phase or rest phase is 0 go back to the previous workout phase
        if (!isStarttimer) {
            this.restTimer.cancel();
            this.workoutTimer.cancel();
            isWorkout = true;
            this.currentreplacedle = getResources().getString(R.string.workout_headline_workout);
            this.currentSet = (restTime == 0) ? currentSet - 1 : currentSet;
            Intent broadcast = new Intent(COUNTDOWN_BROADCAST).putExtra("timer_replacedle", currentreplacedle).putExtra("current_set", currentSet).putExtra("new_timer", workoutTime).putExtra("sets", sets);
            if (isPaused) {
                this.savedTime = workoutTime;
            } else {
                workoutTimer = createWorkoutTimer(workoutTime);
                workoutTimer.start();
            }
            sendBroadcast(broadcast);
        }
    }

    /**
     * Plays a sound for the countdown timer.
     * MediaPlayer is checked for a necessary release beforehand.
     *
     * @param seconds Current seconds to check which sound should be played.
     * @param isWorkout Flag determining if current phase is workout or rest
     */
    private void playSound(int seconds, boolean isWorkout) {
        int soundId = 0;
        boolean isHalfTime = seconds == (int) workoutTime / 2000;
        // Determine which sound should be played
        if (!isSoundsMuted(this)) {
            if (seconds <= 10 && isWorkout && isVoiceCountdownWorkoutEnabled(this)) {
                soundId = getResources().getIdentifier("num_" + seconds, "raw", getPackageName());
            } else if (seconds <= 5 && !isWorkout && isVoiceCountdownRestEnabled(this)) {
                soundId = getResources().getIdentifier("num_" + seconds, "raw", getPackageName());
            } else if (isVoiceHalfTimeEnabled(this) && isWorkout && isHalfTime) {
                soundId = getResources().getIdentifier("half_time", "raw", getPackageName());
            } else if (isWorkoutRythmEnabled(this) && isWorkout && seconds != 0) {
                soundId = seconds != 1 ? getResources().getIdentifier("beep", "raw", getPackageName()) : getResources().getIdentifier("beep_long", "raw", getPackageName());
            }
        }
        if (soundId != 0) {
            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                mediaPlayer.release();
                mediaPlayer = null;
            }
            this.mediaPlayer = MediaPlayer.create(this, soundId);
            mediaPlayer.start();
        }
    }

    /**
     * Calculates the calories burned based on the settings and the duration provided.
     * Calculation is based on MET
     * https://www.fitness-gesundheit.uni-wuppertal.de/fileadmin/fitness-gesundheit/pdf-Dokumente/Publikationen/2015/Prof.Stemper_F_G_4-15.pdf
     *
     * @param workoutDurationSeconds Duration of workout to calculate calories burned.
     * @return Amount of calories burned.
     */
    private int calculateUserCalories(float workoutDurationSeconds) {
        int age = 0;
        int height = 0;
        int weight = 0;
        int circleTrainingMET = 8;
        if (this.settings != null) {
            age = Integer.parseInt(settings.getString(this.getString(R.string.pref_age), "25"));
            height = Integer.parseInt(settings.getString(this.getString(R.string.pref_height), "170"));
            weight = (int) Double.parseDouble(settings.getString(this.getString(R.string.pref_weight), "70"));
        }
        float caloriesPerExercise = circleTrainingMET * (weight * workoutDurationSeconds / 3600);
        return (int) caloriesPerExercise;
    }

    /**
     * Build a notification showing the current progress of the workout.
     * This notification is shown whenever the app goes into the background.
     *
     * @param time The current timer value
     * @return Notification
     */
    public Notification buildNotification(int time) {
        Intent intent = new Intent(this, WorkoutActivity.clreplaced);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Intent buttonIntent = new Intent(NOTIFICATION_BROADCAST);
        PendingIntent buttonPendingIntent = PendingIntent.getBroadcast(this, 4, buttonIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        notiBuilder.setContentIntent(pendingIntent);
        String message = "";
        message = currentreplacedle;
        message += " | " + this.getResources().getString(R.string.workout_notification_time) + ": " + time;
        message += " | " + this.getResources().getString(R.string.workout_info) + ": " + currentSet + "/" + sets;
        // RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.workout_notification);
        boolean paused = (isPaused && !currentreplacedle.equals(getString(R.string.workout_headline_done)));
        int buttonID = paused ? R.drawable.ic_notification_play_24dp : R.drawable.ic_notification_pause_24dp;
        // notificationView.setImageViewResource(R.id.notification_button, buttonID);
        // notificationView.setImageViewResource(R.id.notification_icon,R.drawable.ic_notification);
        // 
        // notificationView.setTextViewText(R.id.notification_replacedle,this.getResources().getString(R.string.app_name));
        // notificationView.setTextViewText(R.id.notification_icon_replacedle,this.getResources().getString(R.string.app_name));
        // notificationView.setTextViewText(R.id.notification_info, message);
        // 
        // notificationView.setOnClickPendingIntent(R.id.notification_button, buttonPendingIntent);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, IntervalTimerApp.CHANNEL_ID).setColor(ContextCompat.getColor(this, R.color.colorAccent)).setSmallIcon(R.drawable.ic_notification).setContentreplacedle(getString(R.string.app_name)).setColorized(true).setAutoCancel(true).addAction(buttonID, paused ? getString(R.string.workout_notification_resume) : getString(R.string.workout_notification_pause), buttonPendingIntent).setContentText(message).setContentInfo(message).setSubText(message).setContentIntent(pendingIntent);
        return builder.build();
    }

    /**
     * Update the notification with current replacedle and timer values.
     *
     * @param time The current timer value
     */
    private void updateNotification(int time) {
        if (isAppInBackground) {
            Notification notification = buildNotification(time);
            notiManager.notify(NOTIFICATION_ID, notification);
        } else if (notiManager != null) {
            notiManager.cancel(NOTIFICATION_ID);
        }
    }

    /**
     * Check if the app is in the background.
     * If so, start a notification showing the current timer.
     *
     * @param isInBackground Sets global flag to determine whether the app is in the background
     */
    public void setIsAppInBackground(boolean isInBackground) {
        this.isAppInBackground = isInBackground;
        // Execute after short delay to prevent short notification popup if workoutActivity is closed
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                int time = currentreplacedle.equals(getString(R.string.workout_headline_done)) ? 0 : (int) Math.ceil(savedTime / 1000.0);
                updateNotification(time);
            }
        }, 700);
    }

    /**
     * Cancel the notification when workout activity is destroyed
     */
    public void workoutClosed() {
        this.isAppInBackground = false;
        notiManager.cancel(NOTIFICATION_ID);
    }

    /**
     * Clean timer stop.
     * Stops all timers, cancels the notification, resets the variables and saves
     * statistics
     */
    public void cleanTimerFinish() {
        this.isAppInBackground = false;
        if (workoutTimer != null) {
            this.workoutTimer.cancel();
        }
        if (restTimer != null) {
            this.restTimer.cancel();
        }
        saveStatistics();
        savedTime = 0;
        isPaused = false;
        isCancelAlert = false;
        isBlockPeriodization = false;
        isStarttimer = false;
        isWorkout = false;
        isPaused = false;
        isCancelAlert = false;
        currentreplacedle = getString(R.string.workout_headline_done);
    }

    /**
     * Returns todays date as int in the form of yyyyMMdd
     * @return Today as in id
     */
    private int getTodayAsID() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String concatDate = dateFormat.format(new Date());
        return Integer.parseInt(concatDate);
    }

    /**
     * Updates the database with calculated global values.
     * Saved values are the workout duration and calories burned.
     */
    private void saveStatistics() {
        database = new PFASQLiteHelper(getBaseContext());
        int id = getTodayAsID();
        statistics = database.getWorkoutData(id);
        if (statistics.getID() == 0) {
            database.addWorkoutDataWithID(new WorkoutSessionData(id, 0, 0));
            statistics = database.getWorkoutData(id);
        }
        int totalTimeSpentTraining = statistics.getWORKOUTTIME() + this.timeSpentWorkingOut;
        int totalCaloriesBurnt = isCaloriesEnabled(this) ? statistics.getCALORIES() + this.caloriesBurned : statistics.getCALORIES();
        database.updateWorkoutData(new WorkoutSessionData(id, totalTimeSpentTraining, totalCaloriesBurnt));
        this.timeSpentWorkingOut = 0;
        this.caloriesBurned = 0;
    }

    /**
     * Multiple checks for what was enabled inside the settings
     */
    public boolean isVoiceCountdownWorkoutEnabled(Context context) {
        if (this.settings != null) {
            return settings.getBoolean(context.getString(R.string.pref_voice_countdown_workout), false);
        }
        return false;
    }

    public boolean isVoiceCountdownRestEnabled(Context context) {
        if (this.settings != null) {
            return settings.getBoolean(context.getString(R.string.pref_voice_countdown_rest), false);
        }
        return false;
    }

    public boolean isWorkoutRythmEnabled(Context context) {
        if (this.settings != null) {
            return settings.getBoolean(context.getString(R.string.pref_sound_rythm), false);
        }
        return false;
    }

    public boolean isVoiceHalfTimeEnabled(Context context) {
        if (this.settings != null) {
            return settings.getBoolean(context.getString(R.string.pref_voice_halftime), false);
        }
        return false;
    }

    public boolean isCaloriesEnabled(Context context) {
        if (this.settings != null) {
            return settings.getBoolean(context.getString(R.string.pref_calories_counter), false);
        }
        return false;
    }

    public boolean isSoundsMuted(Context context) {
        if (this.settings != null) {
            return settings.getBoolean(context.getString(R.string.pref_sounds_muted), true);
        }
        return true;
    }

    /**
     * Getter and Setter
     */
    public long getWorkoutTime() {
        return this.workoutTime;
    }

    public boolean getIsWorkout() {
        return this.isWorkout;
    }

    public long getStartTime() {
        return this.startTime;
    }

    public long getRestTime() {
        return this.restTime;
    }

    public long getBlockRestTime() {
        return this.blockPeriodizationTime;
    }

    public int getSets() {
        return this.sets;
    }

    public int getCaloriesBurned() {
        return this.caloriesBurned;
    }

    public int getCurrentSet() {
        return this.currentSet;
    }

    public String getCurrentreplacedle() {
        return this.currentreplacedle;
    }

    public long getSavedTime() {
        return this.savedTime;
    }

    public boolean getIsPaused() {
        return this.isPaused;
    }

    public void setCancelAlert(boolean isCancelAlert) {
        this.isCancelAlert = isCancelAlert;
    }

    public void setCurrentreplacedle(String replacedle) {
        this.currentreplacedle = replacedle;
    }
}

19 Source : DownTimer.java
with MIT License
from rongcloud

/**
 * [倒计时类]
 *
 * @author devin.hu
 * @version 1.0
 * @date 2014-12-1
 */
public clreplaced DownTimer {

    private final String TAG = DownTimer.clreplaced.getSimpleName();

    private CountDownTimer mCountDownTimer;

    private DownTimerListener listener;

    /**
     * [开始倒计时功能]<br>
     * [倒计为time长的时间,时间间隔为每秒]
     *
     * @param time
     */
    public void startDown(long time) {
        startDown(time, 1000);
    }

    /**
     * [倒计为time长的时间,时间间隔为mills]
     *
     * @param time
     * @param mills
     */
    public void startDown(long time, long mills) {
        mCountDownTimer = new CountDownTimer(time, mills) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (listener != null) {
                    listener.onTick(millisUntilFinished);
                } else {
                    Log.e(TAG, "DownTimerListener 监听不能为空");
                }
            }

            @Override
            public void onFinish() {
                if (listener != null) {
                    listener.onFinish();
                } else {
                    Log.e(TAG, "DownTimerListener 监听不能为空");
                }
                if (mCountDownTimer != null)
                    mCountDownTimer.cancel();
            }
        }.start();
    }

    /**
     * [停止倒计时功能]<br>
     */
    public void stopDown() {
        if (mCountDownTimer != null)
            mCountDownTimer.cancel();
    }

    /**
     * [设置倒计时监听]<br>
     *
     * @param listener
     */
    public void setListener(DownTimerListener listener) {
        this.listener = listener;
    }

    public void finish() {
        if (mCountDownTimer != null)
            mCountDownTimer.onFinish();
    }
}

19 Source : LauncherPresenterImpl.java
with MIT License
from raedev

/**
 * 启动页
 */
public clreplaced LauncherPresenterImpl extends BasicPresenter<LauncherContract.View> implements LauncherContract.Presenter {

    private IRaeServerApi mRaeServerApi;

    private DbAdvert mDbAdvert;

    private AdvertBean mAdvertBean;

    private CountDownTimer mCountDownTimer;

    public LauncherPresenterImpl(LauncherContract.View view) {
        super(view);
        mRaeServerApi = CnblogsApiFactory.getInstance(getContext()).getRaeServerApi();
        mDbAdvert = DbFactory.getInstance().getAdvert();
        // 倒计时
        mCountDownTimer = new CountDownTimer(5000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                getView().onRouteToHome();
            }
        };
    }

    /**
     * 加载本地数据
     */
    private void loadLocalData() {
        AndroidObservable.create(Observable.just(mDbAdvert)).with(this).map(new Function<DbAdvert, AdvertBean>() {

            @Override
            public AdvertBean apply(DbAdvert dbAdvert) {
                return dbAdvert.getLauncherAd();
            }
        }).subscribe(new DefaultObserver<AdvertBean>() {

            @Override
            public void onNext(AdvertBean advertBean) {
                mAdvertBean = advertBean;
                AppMobclickAgent.onLaunchAdExposureEvent(getContext(), advertBean.getAdId(), advertBean.getAdName());
                // 过期时间判断
                if (System.currentTimeMillis() < ApiUtils.parseDate(advertBean.getMAdEndDate()).getTime()) {
                    getView().onLoadImage(advertBean.getAdName(), advertBean.getImageUrl());
                } else {
                    getView().onEmptyImage();
                }
            }

            @Override
            public void onError(Throwable e) {
                getView().onEmptyImage();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 加载启动页数据
     */
    private void loadLauncherData() {
        // 加载首页图
        AndroidObservable.create(mRaeServerApi.getLauncherAd()).with(this).subscribe(new ApiDefaultObserver<AdvertBean>() {

            @Override
            protected void onError(String message) {
                getView().onEmptyImage();
            }

            @Override
            protected void accept(AdvertBean data) {
                // 如果图片发生改变了,重新开始
                AdvertBean local = mDbAdvert.getLauncherAd();
                if (local != null && !TextUtils.equals(local.getImageUrl(), data.getImageUrl())) {
                    mCountDownTimer.cancel();
                    mCountDownTimer.start();
                    getView().onImageChanged();
                }
                // 保存到数据,等待下一次加载
                mDbAdvert.save(data);
                mAdvertBean = data;
                AppMobclickAgent.onLaunchAdExposureEvent(getContext(), data.getAdId(), data.getAdName());
                // 加载图片
                // 过期时间判断
                if (!TextUtils.isEmpty(data.getImageUrl()) && System.currentTimeMillis() < ApiUtils.parseDate(data.getMAdEndDate()).getTime()) {
                    getView().onLoadImage(data.getAdName(), data.getImageUrl());
                } else {
                    getView().onEmptyImage();
                }
            }
        });
    }

    @Override
    protected void onStart() {
        mCountDownTimer.start();
        // 先从本地加载
        loadLocalData();
        // 从网络获取
        loadLauncherData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCountDownTimer.cancel();
    }

    @Override
    public void onAdClick() {
        if (mAdvertBean == null || TextUtils.isEmpty(mAdvertBean.getAdUrl()))
            return;
        // 统计
        AppMobclickAgent.onLaunchAdClickEvent(getContext(), mAdvertBean.getAdId(), mAdvertBean.getAdName());
        mCountDownTimer.cancel();
        // 再跳转网页
        getView().onRouteToWeb(mAdvertBean.getAdUrl());
    }
}

19 Source : Toast.java
with MIT License
from qq283335746

public clreplaced Toast extends CordovaPlugin {

    private static final String ACTION_SHOW_EVENT = "show";

    private static final String ACTION_HIDE_EVENT = "hide";

    private static final int GRAVITY_TOP = Gravity.TOP | Gravity.CENTER_HORIZONTAL;

    private static final int GRAVITY_CENTER = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL;

    private static final int GRAVITY_BOTTOM = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;

    private static final int BASE_TOP_BOTTOM_OFFSET = 20;

    private android.widget.Toast mostRecentToast;

    private ViewGroup viewGroup;

    private static final boolean IS_AT_LEAST_LOLLIPOP = Build.VERSION.SDK_INT >= 21;

    // note that webView.isPaused() is not Xwalk compatible, so tracking it poor-man style
    private boolean isPaused;

    private static CountDownTimer _timer;

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if (ACTION_HIDE_EVENT.equals(action)) {
            hide();
            callbackContext.success();
            return true;
        } else if (ACTION_SHOW_EVENT.equals(action)) {
            if (this.isPaused) {
                return true;
            }
            final JSONObject options = args.getJSONObject(0);
            final String msg = options.getString("message");
            final Spannable message = new SpannableString(msg);
            message.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, msg.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            final String duration = options.getString("duration");
            final String position = options.getString("position");
            final int addPixelsY = options.has("addPixelsY") ? options.getInt("addPixelsY") : 0;
            final JSONObject data = options.has("data") ? options.getJSONObject("data") : null;
            final JSONObject styling = options.optJSONObject("styling");
            cordova.getActivity().runOnUiThread(new Runnable() {

                public void run() {
                    int hideAfterMs;
                    if ("short".equalsIgnoreCase(duration)) {
                        hideAfterMs = 2000;
                    } else if ("long".equalsIgnoreCase(duration)) {
                        hideAfterMs = 4000;
                    } else {
                        // replaceduming a number of ms
                        hideAfterMs = Integer.parseInt(duration);
                    }
                    final android.widget.Toast toast = android.widget.Toast.makeText(IS_AT_LEAST_LOLLIPOP ? cordova.getActivity().getWindow().getContext() : cordova.getActivity().getApplicationContext(), message, // actually controlled by a timer further down
                    android.widget.Toast.LENGTH_LONG);
                    if ("top".equals(position)) {
                        toast.setGravity(GRAVITY_TOP, 0, BASE_TOP_BOTTOM_OFFSET + addPixelsY);
                    } else if ("bottom".equals(position)) {
                        toast.setGravity(GRAVITY_BOTTOM, 0, BASE_TOP_BOTTOM_OFFSET - addPixelsY);
                    } else if ("center".equals(position)) {
                        toast.setGravity(GRAVITY_CENTER, 0, addPixelsY);
                    } else {
                        callbackContext.error("invalid position. valid options are 'top', 'center' and 'bottom'");
                        return;
                    }
                    // if one of the custom layout options have been preplaceded in, draw our own shape
                    if (styling != null && Build.VERSION.SDK_INT >= 16) {
                        // the defaults mimic the default toast as close as possible
                        final String backgroundColor = styling.optString("backgroundColor", "#333333");
                        final String textColor = styling.optString("textColor", "#ffffff");
                        final Double textSize = styling.optDouble("textSize", -1);
                        final double opacity = styling.optDouble("opacity", 0.8);
                        final int cornerRadius = styling.optInt("cornerRadius", 100);
                        final int horizontalPadding = styling.optInt("horizontalPadding", 50);
                        final int verticalPadding = styling.optInt("verticalPadding", 30);
                        GradientDrawable shape = new GradientDrawable();
                        shape.setCornerRadius(cornerRadius);
                        // 0-255, where 0 is an invisible background
                        shape.setAlpha((int) (opacity * 255));
                        shape.setColor(Color.parseColor(backgroundColor));
                        toast.getView().setBackground(shape);
                        final TextView toastTextView;
                        toastTextView = (TextView) toast.getView().findViewById(android.R.id.message);
                        toastTextView.setTextColor(Color.parseColor(textColor));
                        if (textSize > -1) {
                            toastTextView.setTextSize(textSize.floatValue());
                        }
                        toast.getView().setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
                        // this gives the toast a very subtle shadow on newer devices
                        if (Build.VERSION.SDK_INT >= 21) {
                            toast.getView().setElevation(6);
                        }
                    }
                    // On Android >= 5 you can no longer rely on the 'toast.getView().setOnTouchListener',
                    // so created something funky that compares the Toast position to the tap coordinates.
                    if (IS_AT_LEAST_LOLLIPOP) {
                        getViewGroup().setOnTouchListener(new View.OnTouchListener() {

                            @Override
                            public boolean onTouch(View view, MotionEvent motionEvent) {
                                if (motionEvent.getAction() != MotionEvent.ACTION_DOWN) {
                                    return false;
                                }
                                if (mostRecentToast == null || !mostRecentToast.getView().isShown()) {
                                    getViewGroup().setOnTouchListener(null);
                                    return false;
                                }
                                float w = mostRecentToast.getView().getWidth();
                                float startX = (view.getWidth() / 2) - (w / 2);
                                float endX = (view.getWidth() / 2) + (w / 2);
                                float startY;
                                float endY;
                                float g = mostRecentToast.getGravity();
                                float y = mostRecentToast.getYOffset();
                                float h = mostRecentToast.getView().getHeight();
                                if (g == GRAVITY_BOTTOM) {
                                    startY = view.getHeight() - y - h;
                                    endY = view.getHeight() - y;
                                } else if (g == GRAVITY_CENTER) {
                                    startY = (view.getHeight() / 2) + y - (h / 2);
                                    endY = (view.getHeight() / 2) + y + (h / 2);
                                } else {
                                    // top
                                    startY = y;
                                    endY = y + h;
                                }
                                float tapX = motionEvent.getX();
                                float tapY = motionEvent.getY();
                                final boolean tapped = tapX >= startX && tapX <= endX && tapY >= startY && tapY <= endY;
                                return tapped && returnTapEvent(msg, data, callbackContext);
                            }
                        });
                    } else {
                        toast.getView().setOnTouchListener(new View.OnTouchListener() {

                            @Override
                            public boolean onTouch(View view, MotionEvent motionEvent) {
                                return motionEvent.getAction() == MotionEvent.ACTION_DOWN && returnTapEvent(msg, data, callbackContext);
                            }
                        });
                    }
                    // trigger show every 2500 ms for as long as the requested duration
                    _timer = new CountDownTimer(hideAfterMs, 2500) {

                        public void onTick(long millisUntilFinished) {
                            toast.show();
                        }

                        public void onFinish() {
                            toast.cancel();
                        }
                    }.start();
                    mostRecentToast = toast;
                    toast.show();
                    PluginResult pr = new PluginResult(PluginResult.Status.OK);
                    pr.setKeepCallback(true);
                    callbackContext.sendPluginResult(pr);
                }
            });
            return true;
        } else {
            callbackContext.error("toast." + action + " is not a supported function. Did you mean '" + ACTION_SHOW_EVENT + "'?");
            return false;
        }
    }

    private void hide() {
        if (mostRecentToast != null) {
            mostRecentToast.cancel();
            getViewGroup().setOnTouchListener(null);
        }
        if (_timer != null) {
            _timer.cancel();
        }
    }

    private boolean returnTapEvent(String message, JSONObject data, CallbackContext callbackContext) {
        final JSONObject json = new JSONObject();
        try {
            json.put("event", "touch");
            json.put("message", message);
            json.put("data", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        callbackContext.success(json);
        hide();
        return true;
    }

    // lazy init and caching
    private ViewGroup getViewGroup() {
        if (viewGroup == null) {
            viewGroup = (ViewGroup) ((ViewGroup) cordova.getActivity().findViewById(android.R.id.content)).getChildAt(0);
        }
        return viewGroup;
    }

    @Override
    public void onPause(boolean mulreplacedasking) {
        hide();
        this.isPaused = true;
    }

    @Override
    public void onResume(boolean mulreplacedasking) {
        this.isPaused = false;
    }
}

19 Source : MediaMesageInfo.java
with Apache License 2.0
from PAXSTORE

public clreplaced MediaMesageInfo {

    private String savedPath;

    private int template;

    private CountDownTimer countDownTimer;

    private String linkUrl;

    private boolean showSkipButton;

    private Integer countDownTime;

    private String imgUrl;

    private String linkTextColor;

    private String linkTextBgColor;

    private String linkText;

    private String skipButtonText;

    private boolean showLink;

    private String replacedle;

    private String replacedleColor;

    public String getLinkTextBgColor() {
        return linkTextBgColor;
    }

    public void setLinkTextBgColor(String linkTextBgColor) {
        this.linkTextBgColor = linkTextBgColor;
    }

    public String getLinkText() {
        return linkText;
    }

    public void setLinkText(String linkText) {
        this.linkText = linkText;
    }

    public String getSkipButtonText() {
        return skipButtonText;
    }

    public void setSkipButtonText(String skipButtonText) {
        this.skipButtonText = skipButtonText;
    }

    public boolean isShowLink() {
        return showLink;
    }

    public void setShowLink(boolean showLink) {
        this.showLink = showLink;
    }

    public String getreplacedle() {
        return replacedle;
    }

    public void setreplacedle(String replacedle) {
        this.replacedle = replacedle;
    }

    public String getreplacedleColor() {
        return replacedleColor;
    }

    public void setreplacedleColor(String replacedleColor) {
        this.replacedleColor = replacedleColor;
    }

    public int getTemplate() {
        return template;
    }

    public void setTemplate(int template) {
        this.template = template;
    }

    public CountDownTimer getCountDownTimer() {
        return countDownTimer;
    }

    public void setCountDownTimer(CountDownTimer countDownTimer) {
        this.countDownTimer = countDownTimer;
    }

    public String getLinkUrl() {
        return linkUrl;
    }

    public void setLinkUrl(String linkUrl) {
        this.linkUrl = linkUrl;
    }

    public boolean getShowSkipButton() {
        return showSkipButton;
    }

    public void setShowSkipButton(Boolean showSkipButton) {
        this.showSkipButton = showSkipButton;
    }

    public Integer getCountDownTime() {
        return countDownTime;
    }

    public void setCountDownTime(Integer countDownTime) {
        this.countDownTime = countDownTime;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public String getLinkTextColor() {
        return linkTextColor;
    }

    public void setLinkTextColor(String linkTextColor) {
        this.linkTextColor = linkTextColor;
    }

    public String getSavedPath() {
        return savedPath;
    }

    public void setSavedPath(String savedPath) {
        this.savedPath = savedPath;
    }

    @Override
    public String toString() {
        return "MediaMesageInfo{" + "savedPath='" + savedPath + '\'' + ", template=" + template + ", countDownTimer=" + countDownTimer + ", linkUrl='" + linkUrl + '\'' + ", showSkipButton=" + showSkipButton + ", countDownTime=" + countDownTime + ", imgUrl='" + imgUrl + '\'' + ", linkTextColor='" + linkTextColor + '\'' + ", linkTextBgColor='" + linkTextBgColor + '\'' + ", linkText='" + linkText + '\'' + ", skipButtonText=" + skipButtonText + ", showLink=" + showLink + ", replacedle='" + replacedle + '\'' + ", replacedleColor='" + replacedleColor + '\'' + '}';
    }
}

19 Source : MediaMesageInfo.java
with Apache License 2.0
from PAXSTORE

public void setCountDownTimer(CountDownTimer countDownTimer) {
    this.countDownTimer = countDownTimer;
}

19 Source : SignatureUpdateProgressBar.java
with GNU Lesser General Public License v2.1
from open-eid

clreplaced SignatureUpdateProgressBar {

    private static final long PROGRESS_BAR_TIMEOUT_CANCEL = 120 * 1000;

    private static CountDownTimer timeoutTimer;

    void startProgressBar(ProgressBar progressBar) {
        stopProgressBar(progressBar, true);
        progressBar.setMax((int) (PROGRESS_BAR_TIMEOUT_CANCEL / 1000));
        timeoutTimer = new CountDownTimer(PROGRESS_BAR_TIMEOUT_CANCEL, 1000) {

            public void onTick(long millisUntilFinished) {
                progressBar.incrementProgressBy(1);
            }

            public void onFinish() {
                stopProgressBar(progressBar, true);
            }
        }.start();
    }

    void stopProgressBar(ProgressBar progressBar, boolean isTimerStarted) {
        if (isTimerStarted && timeoutTimer != null) {
            progressBar.setProgress(0);
            timeoutTimer.cancel();
        }
    }
}

19 Source : MarkerRefreshController.java
with GNU Affero General Public License v3.0
from omkarmoghe

/**
 * Created by Rohan on 26-07-2016.
 */
public clreplaced MarkerRefreshController {

    final private String TAG = MarkerRefreshController.clreplaced.getName();

    // 1 seconds : heartbeat
    private static final int DEFAULT_UPDATE_INTERVAL = 1000;

    private static final int MARKER_EXPIRED = 1;

    private Handler mHandler;

    private CountDownTimer mTimer;

    private static MarkerRefreshController mInstance;

    private MarkerRefreshController() {
        Handler.Callback callback = new Handler.Callback() {

            @Override
            public boolean handleMessage(Message message) {
                switch(message.what) {
                    case MARKER_EXPIRED:
                        // If Marker Expired
                        if (message.obj instanceof PokemonMarkerExtended) {
                            EventBus.getDefault().post(new MarkerExpired((PokemonMarkerExtended) message.obj));
                            return true;
                        }
                        break;
                }
                return false;
            }
        };
        mHandler = new Handler(callback);
    }

    /*
     * Singleton getter
     */
    public static MarkerRefreshController getInstance() {
        if (mInstance == null) {
            mInstance = new MarkerRefreshController();
        }
        return mInstance;
    }

    /**
     * Cleanup Messages and cancels the timer if it is running.
     */
    public void clear() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mHandler.removeMessages(MARKER_EXPIRED);
    }

    public void startTimer(long duration) {
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (duration <= 0) {
            return;
        }
        final MarkerUpdate event = new MarkerUpdate();
        mTimer = new CountDownTimer(duration, DEFAULT_UPDATE_INTERVAL) {

            @Override
            public void onTick(long l) {
                EventBus.getDefault().post(event);
            }

            @Override
            public void onFinish() {
                mTimer = null;
                EventBus.getDefault().post(event);
            }
        };
        mTimer.start();
    }

    public void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public void clearMessages() {
        mHandler.removeMessages(MARKER_EXPIRED);
    }

    public void postMarker(PokemonMarkerExtended markerData) {
        long time = markerData.getCatchablePokemon().getExpirationTimestampMs() - System.currentTimeMillis();
        if (time > 0) {
            Message message = mHandler.obtainMessage(MARKER_EXPIRED, markerData);
            mHandler.sendMessageDelayed(message, time);
        }
    }
}

19 Source : CountDownButtonHelper.java
with GNU Affero General Public License v3.0
from o2oa

/**
 * 倒计时Button帮助类
 * @see 'http://blog.csdn.net/zhaokaiqiang1992'
 * Created by FancyLou on 2016/6/3.
 */
public clreplaced CountDownButtonHelper {

    // 倒计时timer
    private CountDownTimer countDownTimer;

    // 计时结束的回调接口
    private OnFinishListener listener;

    private Button button;

    /**
     * @param button
     *            需要显示倒计时的Button
     * @param defaultString
     *            默认显示的字符串
     * @param max
     *            需要进行倒计时的最大值,单位是秒
     * @param interval
     *            倒计时的间隔,单位是秒
     */
    public CountDownButtonHelper(final Button button, final String defaultString, int max, int interval) {
        this.button = button;
        // 由于CountDownTimer并不是准确计时,在onTick方法调用的时候,time会有1-10ms左右的误差,这会导致最后一秒不会调用onTick()
        // 因此,设置间隔的时候,默认减去了10ms,从而减去误差。
        // 经过以上的微调,最后一秒的显示时间会由于10ms延迟的积累,导致显示时间比1s长max*10ms的时间,其他时间的显示正常,总时间正常
        countDownTimer = new CountDownTimer(max * 1000, interval * 1000 - 10) {

            @Override
            public void onTick(long time) {
                // 第一次调用会有1-10ms的误差,因此需要+15ms,防止第一个数不显示,第二个数显示2s
                button.setText(((time + 15) / 1000) + "s后重新发送");
                button.setTextColor(FancySkinManager.Companion.instance().getColor(button.getContext(), R.color.z_color_text_hint));
                XLog.debug("CountDownButtonHelper, time = " + (time) + " text = " + ((time + 15) / 1000));
            }

            @Override
            public void onFinish() {
                button.setEnabled(true);
                button.setTextColor(FancySkinManager.Companion.instance().getColor(button.getContext(), R.color.z_color_primary));
                button.setText(defaultString);
                if (listener != null) {
                    listener.finish();
                }
            }
        };
    }

    /**
     * 开始倒计时
     */
    public void start() {
        button.setEnabled(false);
        countDownTimer.start();
    }

    /**
     * 取消计时器
     */
    public void destroy() {
        countDownTimer.cancel();
    }

    /**
     * 设置倒计时结束的监听器
     *
     * @param listener
     */
    public void setOnFinishListener(OnFinishListener listener) {
        this.listener = listener;
    }

    /**
     * 计时结束的回调接口
     *
     * @author zhaokaiqiang
     */
    public interface OnFinishListener {

        public void finish();
    }
}

19 Source : ToolTipRelativeLayout.java
with Apache License 2.0
from mutualmobile

public clreplaced ToolTipRelativeLayout extends RelativeLayout {

    private CountDownTimer timer;

    private ToolTipView toolTipView;

    public ToolTipRelativeLayout(final Context context) {
        super(context);
        initTimer();
    }

    public ToolTipRelativeLayout(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        initTimer();
    }

    public ToolTipRelativeLayout(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
        initTimer();
    }

    private void initTimer() {
        timer = new CountDownTimer(2000, 1000) {

            public void onTick(long millisUntilFinished) {
            }

            public void onFinish() {
                toolTipView.remove();
            }
        };
    }

    public ToolTipView showToolTipForView(float scaleFactor, SeatData pressedSeat, float left, float top) {
        removeViews();
        toolTipView = new ToolTipView(getContext());
        toolTipView.setToolTip(scaleFactor, pressedSeat, left, top);
        addView(toolTipView);
        timer.start();
        return toolTipView;
    }

    public void removeViews() {
        if (timer != null) {
            timer.cancel();
        }
        if (toolTipView != null) {
            toolTipView.remove();
            toolTipView = null;
        }
    }
}

19 Source : CountDownButtonHelper.java
with MIT License
from monsterLin

/**
 * 倒计时Button帮助类
 * @author zhaokaiqiang
 */
public clreplaced CountDownButtonHelper {

    // 倒计时timer
    private CountDownTimer countDownTimer;

    // 计时结束的回调接口
    private OnFinishListener listener;

    private Button button;

    /**
     * @param button
     *            需要显示倒计时的Button
     * @param defaultString
     *            默认显示的字符串
     * @param max
     *            需要进行倒计时的最大值,单位是秒
     * @param interval
     *            倒计时的间隔,单位是秒
     */
    public CountDownButtonHelper(final Button button, final String defaultString, int max, int interval) {
        this.button = button;
        // 由于CountDownTimer并不是准确计时,在onTick方法调用的时候,time会有1-10ms左右的误差,这会导致最后一秒不会调用onTick()
        // 因此,设置间隔的时候,默认减去了10ms,从而减去误差。
        // 经过以上的微调,最后一秒的显示时间会由于10ms延迟的积累,导致显示时间比1s长max*10ms的时间,其他时间的显示正常,总时间正常
        countDownTimer = new CountDownTimer(max * 1000, interval * 1000 - 10) {

            @Override
            public void onTick(long time) {
                // 第一次调用会有1-10ms的误差,因此需要+15ms,防止第一个数不显示,第二个数显示2s
                button.setText(defaultString + "(" + ((time + 15) / 1000) + "秒)");
                Log.d("CountDownButtonHelper", "time = " + (time) + " text = " + ((time + 15) / 1000));
            }

            @Override
            public void onFinish() {
                button.setEnabled(true);
                button.setText(defaultString);
                if (listener != null) {
                    listener.finish();
                }
            }
        };
    }

    /**
     * 开始倒计时
     */
    public void start() {
        button.setEnabled(false);
        countDownTimer.start();
    }

    /**
     * 设置倒计时结束的监听器
     *
     * @param listener 监听器
     */
    public void setOnFinishListener(OnFinishListener listener) {
        this.listener = listener;
    }

    /**
     * 计时结束的回调接口
     *
     * @author zhaokaiqiang
     */
    public interface OnFinishListener {

        void finish();
    }
}

19 Source : WelcomeActivity.java
with Apache License 2.0
from maoqitian

/**
 * @author maoqitian
 * @Description 闪屏页
 * @Time 2019/2/21 0021 20:24
 */
public clreplaced WelcomeActivity extends BaseActivity<WelcomePresenter> implements WelcomeContract.WelcomeView, View.OnClickListener {

    // 测试 dagger2
    /*@Inject
    HomePageBannerModel model;*/
    @BindView(R.id.jump_btn)
    Button mJumpbtn;

    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // DaggerMyComponent.create().inJectWelcomeActivity(this);
        Log.e("毛麒添", "onCreate()");
        ScreenUtils.hideBottomUIMenu(WelcomeActivity.this);
        mJumpbtn.setOnClickListener(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_welcome;
    }

    @Override
    public void jumpToMainActivity() {
        countDownTimer = new MyCountDownTimer(5000 + 200, 1000);
        countDownTimer.start();
        mJumpbtn.setVisibility(View.VISIBLE);
    }

    private void goMainActivity() {
        StartDetailPage.start(this, null, Constants.PAGE_MAIN, Constants.ACTION_MAIN_ACTIVITY);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            ScreenUtils.hideBottomUIMenu(WelcomeActivity.this);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.jump_btn) {
            goMainActivity();
        }
    }

    /**
     * 倒计时计时器
     */
    private clreplaced MyCountDownTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mJumpbtn.setText("跳过(" + millisUntilFinished / 1000 + "s)");
        }

        @Override
        public void onFinish() {
            mJumpbtn.setText("跳过(" + 0 + "s)");
            goMainActivity();
        }
    }
}

19 Source : HomeMultipleRecycleAdapter.java
with Apache License 2.0
from liu-xiao-dong

/**
 * @author admin 数据绑定未进行详细的数据验证,再实际使用中不可取
 */
public clreplaced HomeMultipleRecycleAdapter extends BaseMultiItemQuickAdapter<HomeIndex.ItemInfoListBean, BaseViewHolder> implements BaseQuickAdapter.SpanSizeLookup, BaseQuickAdapter.OnItemChildClickListener {

    private CountDownTimer timer;

    private int maxHasLoadPosition;

    /**
     * 当前position监听
     */
    private PositionChangedListener listener;

    public void setListener(PositionChangedListener listener) {
        this.listener = listener;
    }

    public void resetMaxHasLoadPosition() {
        maxHasLoadPosition = 0;
    }

    public HomeMultipleRecycleAdapter() {
        setSpanSizeLookup(this);
        addItemType(Constant.TYPE_TOP_BANNER, R.layout.homerecycle_item_top_banner);
        addItemType(Constant.TYPE_ICON_LIST, R.layout.homerecycle_item_icon_list);
        addItemType(Constant.TYPE_NEW_USER, R.layout.homerecycle_item_new_user);
        addItemType(Constant.TYPE_JD_BULLETIN, R.layout.homerecycle_item_jd_bulletin);
        addItemType(Constant.TYPE_JD_SPIKE_HEADER, R.layout.homerecycle_item_spike_header);
        addItemType(Constant.TYPE_JD_SPIKE_CONTENT, R.layout.homerecycle_item_spike_content);
        addItemType(Constant.TYPE_SHOW_EVENT_3, R.layout.homerecycle_item_show_event_3);
        addItemType(Constant.TYPE_FIND_GOOD_STUFF, R.layout.homerecycle_item_find_good_stuff);
        addItemType(Constant.TYPE_WIDTH_PROPORTION_211, R.layout.homerecycle_item_type_211);
        addItemType(Constant.TYPE_replacedLE, R.layout.homerecycle_item_type_replacedle);
        addItemType(Constant.TYPE_WIDTH_PROPORTION_22, R.layout.homerecycle_item_type_22);
        addItemType(Constant.TYPE_WIDTH_PROPORTION_1111, R.layout.homerecycle_item_type_1111);
        addItemType(Constant.TYPE_MIDDLE_BANNER, R.layout.homerecycle_item_middle_banner);
        addItemType(Constant.TYPE_SHOW_EVENT_FILL_UP, R.layout.homerecycle_item_show_event_1);
        addItemType(Constant.TYPE_FIND_GOOD_SHOP, R.layout.homerecycle_item_type_find_good_shop);
        addItemType(Constant.TYPE_PREFERRED_LIST, R.layout.homerecycle_item_type_perferred_list);
        addItemType(Constant.TYPE_LIVE, R.layout.homerecycle_item_type_live);
        addItemType(Constant.TYPE_RECOMMENDED_WARE, R.layout.homerecycle_item_type_recommented_ware);
    }

    /**
     * 数据绑定未进行详细的数据验证,在实际使用中不可取
     * @param helper A fully initialized helper.
     * @param item   The item that needs to be displayed.
     * @param position
     */
    @Override
    protected void convert(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        if (listener != null) {
            listener.currentPosition(position);
        }
        if (maxHasLoadPosition < position) {
            maxHasLoadPosition = position;
        }
        if ("topBanner".equals(item.itemType) && maxHasLoadPosition <= position) {
            bindTopBannerData(helper, item, position);
        } else if ("iconList".equals(item.itemType) && maxHasLoadPosition <= position) {
            bindIconListData(helper, item, position);
        } else if ("newUser".equals(item.itemType)) {
            bindNewUserData(helper, item, position);
        } else if ("jdBulletin".equals(item.itemType) && maxHasLoadPosition <= position) {
            bindJDBulletinData(helper, item, position);
        } else if ("jdSpikeHeader".equals(item.itemType) && maxHasLoadPosition <= position) {
            bindJDSpikeHeaderData(helper, item, position);
        } else if ("jdSpikeContent".equals(item.itemType)) {
            bindJDSpikeContentData(helper, item, position);
        } else if ("showEvent".equals(item.itemType)) {
            bindShowEventData(helper, item, position);
        } else if ("findGoodStuff".equals(item.itemType)) {
            bindFindGoodStuffData(helper, item, position);
        } else if ("type_211".equals(item.itemType)) {
            bindType211Data(helper, item, position);
        } else if ("type_replacedle".equals(item.itemType)) {
            bindTypereplacedleData(helper, item, position);
        } else if ("type_22".equals(item.itemType)) {
            bindType22Data(helper, item, position);
        } else if ("type_1111".equals(item.itemType)) {
            bindType1111Data(helper, item, position);
        } else if ("type_middleBanner".equals(item.itemType)) {
            bindTypeMiddleBannerData(helper, item, position);
        } else if ("showEventFillUp".equals(item.itemType)) {
            bindShowEventFillUpData(helper, item, position);
        } else if ("findGoodShop".equals(item.itemType)) {
            bindFindGoodShopData(helper, item, position);
        } else if ("preferredList".equals(item.itemType)) {
            bindPreferredListData(helper, item, position);
        } else if ("live".equals(item.itemType)) {
            bindLiveData(helper, item, position);
        } else if ("recommended_ware".equals(item.itemType)) {
            bindRecommendedWareData(helper, item, position);
        }
    }

    private void bindRecommendedWareData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.recommended_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        helper.setText(R.id.recommended_replacedle, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.recommended_price, item.itemContentList.get(0).itemSubreplacedle);
    }

    private void bindLiveData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.type_live_item_one_img1)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type_live_item_two_img1)).setImageURI(item.itemContentList.get(1).imageUrl);
        ((ExpandImageView) helper.getView(R.id.live_icon)).setImageURI(item.itemContentList.get(0).itemBackgroundImageUrl);
        ((ExpandImageView) helper.getView(R.id.live_icon1)).setImageURI(item.itemContentList.get(1).itemBackgroundImageUrl);
        helper.setText(R.id.type_live_item_one_replacedle, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.type_live_one_sub_replacedle, item.itemContentList.get(0).itemSubreplacedle);
        // helper.setText(R.id.type_find_good_shop_item_one_shop_name,item.itemContentList.get(0).itemRecommendedLanguage);
        helper.setText(R.id.type_live_item_two_replacedle, item.itemContentList.get(1).itemreplacedle);
        helper.setText(R.id.type_live_item_two_sub_replacedle, item.itemContentList.get(1).itemSubreplacedle);
    // helper.setText(R.id.type_find_good_shop_item_two_shop_name,item.itemContentList.get(1).itemRecommendedLanguage);
    }

    private void bindPreferredListData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.type_preferred_list_item_two_img1)).setImageURI(item.itemContentList.get(1).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type_preferred_list_item_two_img2)).setImageURI(item.itemContentList.get(1).itemBackgroundImageUrl);
        ((ExpandImageView) helper.getView(R.id.type_preferred_list_item_one_img1)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type_preferred_list_item_one_img2)).setImageURI(item.itemContentList.get(0).itemBackgroundImageUrl);
        helper.setText(R.id.type_preferred_list_item_one_replacedle, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.type_preferred_list_item_two_replacedle, item.itemContentList.get(1).itemreplacedle);
    }

    private void bindFindGoodShopData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.type_find_good_shop_item_two_img1)).setImageURI(item.itemContentList.get(1).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type_find_good_shop_item_two_img2)).setImageURI(item.itemContentList.get(1).itemBackgroundImageUrl);
        ((ExpandImageView) helper.getView(R.id.type_find_good_shop_item_one_img1)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type_find_good_shop_item_one_img2)).setImageURI(item.itemContentList.get(0).itemBackgroundImageUrl);
        helper.setText(R.id.type_find_good_shop_item_one_replacedle, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.type_find_good_shop_item_one_sub_replacedle, item.itemContentList.get(0).itemSubreplacedle);
        helper.setText(R.id.type_find_good_shop_item_one_shop_name, item.itemContentList.get(0).itemRecommendedLanguage);
        helper.setText(R.id.type_find_good_shop_item_two_replacedle, item.itemContentList.get(1).itemreplacedle);
        helper.setText(R.id.type_find_good_shop_item_two_sub_replacedle, item.itemContentList.get(1).itemSubreplacedle);
        helper.setText(R.id.type_find_good_shop_item_two_shop_name, item.itemContentList.get(1).itemRecommendedLanguage);
    }

    private void bindShowEventFillUpData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.show_event_fill_up)).setImageURI(item.itemContentList.get(0).imageUrl);
    }

    private void bindTypeMiddleBannerData(BaseViewHolder helper, final HomeIndex.ItemInfoListBean item, int position) {
        BGABanner banner = helper.getView(R.id.middle_banner);
        banner.setDelegate(new BGABanner.Delegate<View, HomeIndex.ItemInfoListBean.ItemContentListBean>() {

            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, HomeIndex.ItemInfoListBean.ItemContentListBean model, int position) {
                Toast.makeText(itemView.getContext(), "" + item.itemContentList.get(position).clickUrl, Toast.LENGTH_SHORT).show();
            }
        });
        banner.setAdapter(new BGABanner.Adapter<View, HomeIndex.ItemInfoListBean.ItemContentListBean>() {

            @Override
            public void fillBannerItem(BGABanner banner, View itemView, HomeIndex.ItemInfoListBean.ItemContentListBean model, int position) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView) itemView.findViewById(R.id.type_item_middle_banner_content);
                simpleDraweeView.setImageURI(Uri.parse(model.imageUrl));
            }
        });
        banner.setData(R.layout.homerecycle_middle_banner_content, item.itemContentList, null);
    }

    private void bindType1111Data(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.type1111_item_one_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type1111_item_two_img)).setImageURI(item.itemContentList.get(1).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type1111_item_three_img)).setImageURI(item.itemContentList.get(2).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type1111_item_four_img)).setImageURI(item.itemContentList.get(3).imageUrl);
        helper.setText(R.id.type1111_item_one_replacedle, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.type1111_item_one_sub_replacedle, item.itemContentList.get(0).itemSubreplacedle);
        helper.setText(R.id.type1111_item_three_replacedle, item.itemContentList.get(2).itemreplacedle);
        helper.setText(R.id.type1111_item_three_sub_replacedle, item.itemContentList.get(2).itemSubreplacedle);
        helper.setText(R.id.type1111_item_two_replacedle, item.itemContentList.get(1).itemreplacedle);
        helper.setText(R.id.type1111_item_two_sub_replacedle, item.itemContentList.get(1).itemSubreplacedle);
        helper.setText(R.id.type1111_item_four_replacedle, item.itemContentList.get(3).itemreplacedle);
        helper.setText(R.id.type1111_item_four_sub_replacedle, item.itemContentList.get(3).itemSubreplacedle);
        setRecommendedLanguage(helper, item, R.id.type1111_item_one_subscript, 0);
        setRecommendedLanguage(helper, item, R.id.type1111_item_two_subscript, 1);
        setRecommendedLanguage(helper, item, R.id.type1111_item_three_subscript, 2);
        setRecommendedLanguage(helper, item, R.id.type1111_item_four_subscript, 3);
    }

    private void bindType22Data(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.type22_item_one_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.type22_item_two_img)).setImageURI(item.itemContentList.get(1).imageUrl);
        helper.setText(R.id.type22_item_one_replacedle, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.type22_item_one_sub_replacedle, item.itemContentList.get(0).itemSubreplacedle);
        helper.setText(R.id.type22_item_two_replacedle, item.itemContentList.get(1).itemreplacedle);
        helper.setText(R.id.type22_item_two_sub_replacedle, item.itemContentList.get(1).itemSubreplacedle);
        setRecommendedLanguage(helper, item, R.id.type22_item_one_recommendedLanguage, 0);
        setRecommendedLanguage(helper, item, R.id.type22_item_two_recommendedLanguage, 1);
    }

    /**
     * 填充下标 或 推荐 内容
     *
     * @param helper
     * @param item
     * @param id
     * @param index
     */
    private void setRecommendedLanguage(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int id, int index) {
        String itemRecommendedLanguage = item.itemContentList.get(index).itemRecommendedLanguage;
        if (TextUtils.isEmpty(itemRecommendedLanguage)) {
            helper.getView(id).setVisibility(View.GONE);
        } else {
            helper.getView(id).setVisibility(View.VISIBLE);
            helper.setText(id, itemRecommendedLanguage);
            if ("loveLife".equals(item.module)) {
                helper.getView(id).setBackgroundResource(R.drawable.home_love_life_subscript_gradient_bg);
            } else if ("enjoyQuality".equals(item.module)) {
                helper.getView(id).setBackgroundResource(R.drawable.home_enjoy_quality_subscript_gradient_bg);
            } else if ("buyFeatures".equals(item.module)) {
                helper.getView(id).setBackgroundResource(R.drawable.home_buy_feature_subscript_gradient_bg);
            }
        }
    }

    private void bindTypereplacedleData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.type_replacedle_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        if (!TextUtils.isEmpty(item.itemContentList.get(0).itemreplacedle)) {
            helper.getView(R.id.type_replacedle_more_ll).setVisibility(View.VISIBLE);
            helper.setText(R.id.type_replacedle_more_text, item.itemContentList.get(0).itemreplacedle);
            if ("loveLife".equals(item.module) || "findGoodShop".equals(item.module) || "preferredList".equals(item.module) || "live".equals(item.module)) {
                ((ExpandImageView) helper.getView(R.id.type_replacedle_arrow_img)).setImageResource(R.drawable.orange_arrow);
            } else if ("goShopping".equals(item.module)) {
                ((ExpandImageView) helper.getView(R.id.type_replacedle_arrow_img)).setImageResource(R.drawable.go_shopping_rt);
            }
        } else {
            helper.getView(R.id.type_replacedle_more_ll).setVisibility(View.GONE);
        }
    }

    private void bindType211Data(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        helper.setText(R.id.item_one_replacedle, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.item_two_replacedle, item.itemContentList.get(1).itemreplacedle);
        helper.setText(R.id.item_three_replacedle, item.itemContentList.get(2).itemreplacedle);
        helper.setText(R.id.item_one_sub_replacedle, item.itemContentList.get(0).itemSubreplacedle);
        helper.setText(R.id.item_two_sub_replacedle, item.itemContentList.get(1).itemSubreplacedle);
        helper.setText(R.id.item_three_sub_replacedle, item.itemContentList.get(2).itemSubreplacedle);
        helper.setText(R.id.item_one_subscript, item.itemContentList.get(0).itemRecommendedLanguage);
        ((ExpandImageView) helper.getView(R.id.item_one_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.item_two_img)).setImageURI(item.itemContentList.get(1).imageUrl);
        ((ExpandImageView) helper.getView(R.id.item_three_img)).setImageURI(item.itemContentList.get(2).imageUrl);
        if ("ranking".equals(item.module)) {
            helper.getView(R.id.item_one_subscript).setBackgroundResource(R.drawable.home_love_life_subscript_gradient_bg);
        } else if ("buyFeatures".equals(item.module)) {
            helper.getView(R.id.item_one_subscript).setBackgroundResource(R.drawable.home_buy_feature_subscript_gradient_bg);
        }
    }

    private void bindFindGoodStuffData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.find_good_stuff_left_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.find_good_stuff_right_img)).setImageURI(item.itemContentList.get(1).imageUrl);
    }

    private void bindShowEventData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.show_event_left_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.show_event_middle_img)).setImageURI(item.itemContentList.get(1).imageUrl);
        ((ExpandImageView) helper.getView(R.id.show_event_right_img)).setImageURI(item.itemContentList.get(2).imageUrl);
    }

    private void bindJDSpikeContentData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        if (item.itemContentList == null || item.itemContentList.size() <= 0)
            return;
        RecyclerView recyclerView = helper.getView(R.id.spike_content_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        SpikeContentAdapter adapter = new SpikeContentAdapter(R.layout.homerecycle_item_spike_content, item.itemContentList);
        recyclerView.setAdapter(adapter);
    }

    private void bindJDSpikeHeaderData(final BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        helper.setText(R.id.spike_time_field, item.itemContentList.get(0).itemreplacedle);
        helper.setText(R.id.spike_header_desc, item.itemContentList.get(0).itemSubreplacedle);
        String time = item.itemContentList.get(0).itemRecommendedLanguage;
        if (TextUtils.isEmpty(time) || !time.matches("^[0-9]*$"))
            return;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new CountDownTimer(Long.parseLong(time), 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                long temp = millisUntilFinished / 1000;
                long hours = temp / 3600;
                long minutes = (temp - (3600 * hours)) / 60;
                long seconds = temp - (3600 * hours) - (60 * minutes);
                helper.setText(R.id.spike_time_hour, hours > 9 ? "" + hours : "0" + hours);
                helper.setText(R.id.spike_time_minute, minutes > 9 ? "" + minutes : "0" + minutes);
                helper.setText(R.id.spike_time_seconds, seconds > 9 ? "" + seconds : "0" + seconds);
            }

            @Override
            public void onFinish() {
                helper.setText(R.id.spike_time_hour, "00");
                helper.setText(R.id.spike_time_minute, "00");
                helper.setText(R.id.spike_time_seconds, "00");
            }
        }.start();
    }

    private void bindJDBulletinData(BaseViewHolder helper, final HomeIndex.ItemInfoListBean item, int position) {
        UpDownViewSwitcher viewSwitcher = helper.getView(R.id.home_view_switcher);
        viewSwitcher.setSwitcheNextViewListener(new UpDownViewSwitcher.SwitchNextViewListener() {

            @Override
            public void switchTONextView(View nextView, int index) {
                if (nextView == null)
                    return;
                final String tag = item.itemContentList.get(index % item.itemContentList.size()).itemreplacedle;
                final String tag1 = item.itemContentList.get(index % item.itemContentList.size()).itemSubreplacedle;
                ((TextView) nextView.findViewById(R.id.textview)).setText(tag1);
                ((TextView) nextView.findViewById(R.id.switch_replacedle_text)).setText(tag);
                nextView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Toast.makeText(v.getContext().getApplicationContext(), tag, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        viewSwitcher.setContentLayout(R.layout.switch_view);
    }

    private void bindNewUserData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        ((ExpandImageView) helper.getView(R.id.new_user_bg_img)).setImageURI(item.itemContentList.get(0).imageUrl);
        ((ExpandImageView) helper.getView(R.id.new_user_red_envelopes)).setImageURI(item.itemContentList.get(1).imageUrl);
        ((ExpandImageView) helper.getView(R.id.new_uer_free_postage)).setImageURI(item.itemContentList.get(2).imageUrl);
        ((ExpandImageView) helper.getView(R.id.new_user_basic_necessities_of_life)).setImageURI(item.itemContentList.get(3).imageUrl);
        ((ExpandImageView) helper.getView(R.id.new_user_packs)).setImageURI(item.itemContentList.get(4).imageUrl);
    }

    private void bindIconListData(BaseViewHolder helper, HomeIndex.ItemInfoListBean item, int position) {
        if (item.itemContentList.size() == 10) {
            helper.setText(R.id.icon_list_one_replacedle, item.itemContentList.get(0).itemreplacedle);
            helper.addOnClickListener(R.id.icon_list_one);
            helper.addOnClickListener(R.id.icon_list_one_replacedle);
            setOnItemChildClickListener(this);
            helper.setText(R.id.icon_list_two_replacedle, item.itemContentList.get(1).itemreplacedle);
            helper.setText(R.id.icon_list_three_replacedle, item.itemContentList.get(2).itemreplacedle);
            helper.setText(R.id.icon_list_four_replacedle, item.itemContentList.get(3).itemreplacedle);
            helper.setText(R.id.icon_list_five_replacedle, item.itemContentList.get(4).itemreplacedle);
            helper.setText(R.id.icon_list_six_replacedle, item.itemContentList.get(5).itemreplacedle);
            helper.setText(R.id.icon_list_seven_replacedle, item.itemContentList.get(6).itemreplacedle);
            helper.setText(R.id.icon_list_eight_replacedle, item.itemContentList.get(7).itemreplacedle);
            helper.setText(R.id.icon_list_nine_replacedle, item.itemContentList.get(8).itemreplacedle);
            helper.setText(R.id.icon_list_ten_replacedle, item.itemContentList.get(9).itemreplacedle);
            ((ExpandImageView) helper.getView(R.id.icon_list_one)).setImageURI(item.itemContentList.get(0).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_two)).setImageURI(item.itemContentList.get(1).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_three)).setImageURI(item.itemContentList.get(2).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_four)).setImageURI(item.itemContentList.get(3).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_five)).setImageURI(item.itemContentList.get(4).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_six)).setImageURI(item.itemContentList.get(5).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_seven)).setImageURI(item.itemContentList.get(6).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_eight)).setImageURI(item.itemContentList.get(7).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_nine)).setImageURI(item.itemContentList.get(8).imageUrl);
            ((ExpandImageView) helper.getView(R.id.icon_list_ten)).setImageURI(item.itemContentList.get(9).imageUrl);
            if (!TextUtils.isEmpty(item.itemContentList.get(0).itemBackgroundImageUrl)) {
                ((ExpandImageView) helper.getView(R.id.icon_list_bg)).setImageURI(item.itemContentList.get(0).itemBackgroundImageUrl);
            } else {
                ((ExpandImageView) helper.getView(R.id.icon_list_bg)).setImageResource(0);
            }
            if (!TextUtils.isEmpty(item.itemContentList.get(0).itemSubreplacedle)) {
                if ("white".equals(item.itemContentList.get(0).itemSubreplacedle)) {
                    ((TextView) helper.getView(R.id.icon_list_one_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_two_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_three_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_four_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_five_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_six_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_seven_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_eight_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_nine_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                    ((TextView) helper.getView(R.id.icon_list_ten_replacedle)).setTextColor(mContext.getResources().getColor(R.color.white));
                }
            } else {
                ((TextView) helper.getView(R.id.icon_list_one_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_two_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_three_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_four_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_five_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_six_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_seven_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_eight_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_nine_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
                ((TextView) helper.getView(R.id.icon_list_ten_replacedle)).setTextColor(mContext.getResources().getColor(R.color.black_font));
            }
        }
    }

    /**
     * 绑定banner数据
     *
     * @param helper
     * @param item
     * @param position
     */
    private void bindTopBannerData(BaseViewHolder helper, final HomeIndex.ItemInfoListBean item, int position) {
        BGABanner banner = helper.getView(R.id.banner);
        banner.setDelegate(new BGABanner.Delegate<View, HomeIndex.ItemInfoListBean.ItemContentListBean>() {

            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, HomeIndex.ItemInfoListBean.ItemContentListBean model, int position) {
                Toast.makeText(itemView.getContext(), "" + item.itemContentList.get(position).clickUrl, Toast.LENGTH_SHORT).show();
            }
        });
        banner.setAdapter(new BGABanner.Adapter<View, HomeIndex.ItemInfoListBean.ItemContentListBean>() {

            @Override
            public void fillBannerItem(BGABanner banner, View itemView, HomeIndex.ItemInfoListBean.ItemContentListBean model, int position) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView) itemView.findViewById(R.id.sdv_item_fresco_content);
                simpleDraweeView.setImageURI(Uri.parse(model.imageUrl));
            }
        });
        banner.setData(R.layout.homerecycle_top_banner_content, item.itemContentList, null);
    }

    @Override
    public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
        return mData.get(position).getSpanSize();
    }

    @Override
    public boolean onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        int id = view.getId();
        if (id == R.id.icon_list_one) {
            ARouter.getInstance().build("/test1/activity").navigation(view.getContext());
        }
        return false;
    }
}

19 Source : AlwaysMarqueeTextView.java
with Apache License 2.0
from Klaus3d3

/*

    Imported from:
    https://github.com/Noobknight/MusicPlayer/blob/master/app/src/main/java/com/tadev/musicplayer/supports/design/AlwaysMarqueeTextView.java
    Modified to add a countdown to automatically starting the marquee after 1s

 */
public clreplaced AlwaysMarqueeTextView extends AppCompatTextView {

    protected boolean a;

    public AlwaysMarqueeTextView(Context context) {
        super(context);
        a = false;
        setAlwaysMarquee(true);
        setAlwaysMarquee(false);
        countDownTimer.start();
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attributeset) {
        super(context, attributeset);
        a = false;
        countDownTimer.start();
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attributeset, int i) {
        super(context, attributeset, i);
        a = false;
        countDownTimer.start();
    }

    CountDownTimer countDownTimer = new CountDownTimer(1000, 1000) {

        @Override
        public void onTick(long l) {
        }

        @Override
        public void onFinish() {
            setAlwaysMarquee(true);
        }
    };

    public boolean isFocused() {
        return a || super.isFocused();
    }

    public void setAlwaysMarquee(boolean flag) {
        setSelected(flag);
        setSingleLine(flag);
        if (flag)
            setEllipsize(TextUtils.TruncateAt.MARQUEE);
        a = flag;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if (focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if (focused)
            super.onWindowFocusChanged(focused);
    }
}

19 Source : MainActivity.java
with Apache License 2.0
from KieronQuinn

public clreplaced MainActivity extends AppCompatActivity {

    // List to hold all settings
    private ArrayList<BaseSetting> settingList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get in and out settings. In is the main setting, which defines the order and state of a page, but does not always contain them all. Out contains them all, but no ordering
        String springboard_widget_order_in = Settings.System.getString(getContentResolver(), "springboard_widget_order_in");
        String springboard_widget_order_out = Settings.System.getString(getContentResolver(), "springboard_widget_order_out");
        // Create empty list
        settingList = new ArrayList<>();
        try {
            // Parse JSON
            JSONObject root = new JSONObject(springboard_widget_order_in);
            JSONArray data = root.getJSONArray("data");
            List<String> addedComponents = new ArrayList<>();
            // Data array contains all the elements
            for (int x = 0; x < data.length(); x++) {
                // Get item
                JSONObject item = data.getJSONObject(x);
                // srl is the position, stored as a string for some reason
                int srl = Integer.parseInt(item.getString("srl"));
                // State is stored as an integer when it would be better as a boolean so convert it
                boolean enable = item.getInt("enable") == 1;
                // Create springboard item with the package name, clreplaced name and state
                final SpringboardItem springboardItem = new SpringboardItem(item.getString("pkg"), item.getString("cls"), enable);
                // Create a setting (extending switch) with the relevant data and a callback
                SpringboardSetting springboardSetting = new SpringboardSetting(null, getreplacedle(springboardItem.getPackageName()), formatComponentName(springboardItem.getClreplacedName()), new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        // Ignore on create to reduce load
                        if (!compoundButton.isPressed())
                            return;
                        // Update state
                        springboardItem.setEnabled(b);
                        // Save
                        save();
                    }
                }, springboardItem.isEnable(), springboardItem);
                // Store component name for later
                addedComponents.add(springboardItem.getClreplacedName());
                try {
                    // Attempt to add at position, may cause exception
                    settingList.add(srl, springboardSetting);
                } catch (IndexOutOfBoundsException e) {
                    // Add at top as position won't work
                    settingList.add(springboardSetting);
                }
            }
            // Parse JSON
            JSONObject rootOut = new JSONObject(springboard_widget_order_out);
            JSONArray dataOut = rootOut.getJSONArray("data");
            // Loop through main data array
            for (int x = 0; x < data.length(); x++) {
                // Get item
                JSONObject item = dataOut.getJSONObject(x);
                // Get component name to check list
                String componentName = item.getString("cls");
                if (!addedComponents.contains(componentName)) {
                    // Get if item is enabled, this time stored as a string (why?)
                    boolean enable = item.getString("enable").equals("true");
                    // Create item with the package name, clreplaced name and state
                    final SpringboardItem springboardItem = new SpringboardItem(item.getString("pkg"), item.getString("cls"), enable);
                    // Create setting with all the relevant data
                    SpringboardSetting springboardSetting = new SpringboardSetting(null, getreplacedle(springboardItem.getPackageName()), formatComponentName(springboardItem.getClreplacedName()), new CompoundButton.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                            if (!compoundButton.isPressed())
                                return;
                            springboardItem.setEnabled(b);
                            save();
                        }
                    }, springboardItem.isEnable(), springboardItem);
                    // Add clreplaced name to list to prevent it being adding more than once
                    addedComponents.add(springboardItem.getClreplacedName());
                    // Add setting to main list
                    settingList.add(springboardSetting);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Empty settings list can be confusing to the user, and is quite common, so we'll add the FAQ to save them having to read the OP (oh the horror)
        if (settingList.size() == 0) {
            // Add error message
            settingList.add(new TextSetting(getString(R.string.error_loading), new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    // Restart
                    startActivity(new Intent(MainActivity.this, MainActivity.clreplaced));
                    finish();
                }
            }));
        }
        // Add main header to top (pos 0)
        settingList.add(0, new HeaderSetting(getString(R.string.springboard)));
        // Create adapter with setting list and a change listener to save the settings on move
        Adapter adapter = new Adapter(this, settingList, new Adapter.ChangeListener() {

            @Override
            public void onChange() {
                checkSave();
            }
        });
        // Create recyclerview as layout
        RecyclerView recyclerView = new RecyclerView(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        // Setup drag to move using the helper
        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(adapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
        touchHelper.attachToRecyclerView(recyclerView);
        // Add padding for the watch
        recyclerView.setPadding((int) getResources().getDimension(R.dimen.padding_round_small), 0, (int) getResources().getDimension(R.dimen.padding_round_small), (int) getResources().getDimension(R.dimen.padding_round_large));
        recyclerView.setClipToPadding(false);
        // Set the view
        setContentView(recyclerView);
    }

    // Get an app name from the package name
    private String getreplacedle(String pkg) {
        PackageManager packageManager = getPackageManager();
        try {
            return String.valueOf(packageManager.getApplicationLabel(packageManager.getApplicationInfo(pkg, 0)));
        } catch (PackageManager.NameNotFoundException e) {
            return getString(R.string.unknown);
        }
    }

    private void save() {
        // Create a blank array
        JSONArray data = new JSONArray();
        // Hold position for use as srl
        int pos = 0;
        for (BaseSetting springboardSetting : settingList) {
            // Ignore if not a springboard setting
            if (!(springboardSetting instanceof SpringboardSetting))
                continue;
            // Get item
            SpringboardItem springboardItem = ((SpringboardSetting) springboardSetting).getSpringboardItem();
            JSONObject item = new JSONObject();
            // Setup item with data from the item
            try {
                item.put("pkg", springboardItem.getPackageName());
                item.put("cls", springboardItem.getClreplacedName());
                item.put("srl", String.valueOf(pos));
                item.put("enable", springboardItem.isEnable() ? "1" : "0");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            // Add to list and increment position
            data.put(item);
            pos++;
        }
        // Add to root object
        JSONObject root = new JSONObject();
        try {
            root.put("data", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Save setting
        Settings.System.putString(getContentResolver(), "springboard_widget_order_in", root.toString());
        // Notify user
        Toast.makeText(this, getString(R.string.saved), Toast.LENGTH_LONG).show();
    }

    // Countdown timer to prevent saving too often
    private CountDownTimer countDownTimer;

    private void checkSave() {
        // Create timer if not already, for 2 seconds. Call save after completion
        if (countDownTimer == null)
            countDownTimer = new CountDownTimer(2000, 2000) {

                @Override
                public void onTick(long l) {
                }

                @Override
                public void onFinish() {
                    save();
                }
            };
        // Cancel and start timer. This means that this method must be called ONCE in 2 seconds before save will be called, it prevents save from being called more than once every 2 seconds (buffers moving)
        countDownTimer.cancel();
        countDownTimer.start();
    }

    // Get last part of component name
    private String formatComponentName(String componentName) {
        // Ignore if no . and just return component name
        if (!componentName.contains("."))
            return componentName;
        // Return just the last section of component name
        return componentName.substring(componentName.lastIndexOf(".") + 1);
    }
}

19 Source : CountDownTimerUtils.java
with MIT License
from hapramp

public clreplaced CountDownTimerUtils {

    final static long MILLIS_IN_DAY = 86400000;

    final static long MILLIS_IN_HOUR = 3600000;

    final static long MILLIS_IN_MIN = 60000;

    final static long MILLIS_IN_SEC = 1000;

    private CountDownTimer timer;

    public void setTimerWith(long finishTime, long tickInterval, final TimerUpdateListener timerUpdateListener) {
        timer = new CountDownTimer(finishTime, tickInterval) {

            public void onTick(long millisLeft) {
                if (timerUpdateListener != null) {
                    timerUpdateListener.onRunningTimeUpdate(getDescriptiveCountdown(millisLeft));
                }
            }

            public void onFinish() {
                if (timerUpdateListener != null) {
                    timerUpdateListener.onFinished();
                }
            }
        };
    }

    public static String getDescriptiveCountdown(long millisLeft) {
        StringBuilder builder = new StringBuilder();
        long day, hour, min, sec;
        long consumed = 0;
        if (millisLeft >= MILLIS_IN_DAY) {
            day = millisLeft / MILLIS_IN_DAY;
            consumed = day * MILLIS_IN_DAY;
            hour = (millisLeft - consumed) / MILLIS_IN_HOUR;
            consumed += hour * MILLIS_IN_HOUR;
            min = (millisLeft - consumed) / MILLIS_IN_MIN;
            consumed += min * MILLIS_IN_MIN;
            sec = (millisLeft - consumed) / MILLIS_IN_SEC;
            builder.append(String.format(Locale.US, "%02d : ", day)).append(String.format(Locale.US, "%02d : ", hour)).append(String.format(Locale.US, "%02d : ", min)).append(String.format(Locale.US, "%02d", sec));
        } else if (millisLeft >= MILLIS_IN_HOUR) {
            hour = (millisLeft - consumed) / MILLIS_IN_HOUR;
            consumed = hour * MILLIS_IN_HOUR;
            min = (millisLeft - consumed) / MILLIS_IN_MIN;
            consumed += min * MILLIS_IN_MIN;
            sec = (millisLeft - consumed) / MILLIS_IN_SEC;
            builder.append(String.format(Locale.US, "%02d Hr. ", hour)).append(String.format(Locale.US, "%02d Min ", min)).append(String.format(Locale.US, "%02d Sec ", sec));
        } else if (millisLeft >= MILLIS_IN_MIN) {
            min = (millisLeft - consumed) / MILLIS_IN_MIN;
            consumed = min * MILLIS_IN_MIN;
            sec = (millisLeft - consumed) / MILLIS_IN_SEC;
            builder.append(String.format(Locale.US, "%02d Min ", min)).append(String.format(Locale.US, "%02d Sec ", sec));
        } else if (millisLeft >= MILLIS_IN_SEC) {
            sec = millisLeft / MILLIS_IN_SEC;
            builder.append(String.format(Locale.US, "%02d Second", sec));
        }
        return builder.toString();
    }

    public void start() {
        if (timer != null) {
            timer.start();
        }
    }

    public void cancel() {
        if (timer != null) {
            timer.cancel();
        }
    }

    public interface TimerUpdateListener {

        void onFinished();

        void onRunningTimeUpdate(String updateTime);
    }
}

19 Source : CountDownTimerService.java
with MIT License
from google-udacity-india-scholars

public clreplaced CountDownTimerService extends Service {

    public static final int ID = 1;

    LocalBroadcastManager broadcaster;

    private CountDownTimer countDownTimer;

    private SharedPreferences preferences;

    private int newWorkSessionCount;

    private int currentlyRunningServiceType;

    public CountDownTimerService() {
    }

    @Override
    public void onCreate() {
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        broadcaster = LocalBroadcastManager.getInstance(this);
    }

    @Override
    public void onDestroy() {
        countDownTimer.cancel();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        long TIME_PERIOD = intent.getLongExtra("time_period", 0);
        long TIME_INTERVAL = intent.getLongExtra("time_interval", 0);
        currentlyRunningServiceType = Utils.retrieveCurrentlyRunningServiceType(preferences, this);
        Intent notificationIntent = new Intent(this, MainActivity.clreplaced);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        // For "Complete" button - Intent and PendingIntent
        Intent completeIntent = new Intent(this, StopTimerActionReceiver.clreplaced).putExtra(INTENT_NAME_ACTION, INTENT_VALUE_COMPLETE);
        PendingIntent completeActionPendingIntent = PendingIntent.getBroadcast(this, 1, completeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // For "Cancel" button - Intent and PendingIntent
        Intent cancelIntent = new Intent(this, StopTimerActionReceiver.clreplaced).putExtra(INTENT_NAME_ACTION, INTENT_VALUE_CANCEL);
        PendingIntent cancelActionPendingIntent = PendingIntent.getBroadcast(this, 0, cancelIntent, 0);
        Notification.Builder notificationBuilder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationBuilder = new Notification.Builder(this, CHANNEL_ID);
        } else {
            notificationBuilder = new Notification.Builder(this);
        }
        notificationBuilder = notificationBuilder.setSmallIcon(R.drawable.ic_notification).setContentIntent(pendingIntent).setOngoing(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            notificationBuilder = notificationBuilder.setWhen(System.currentTimeMillis() + TIME_PERIOD).setUsesChronometer(true).setChronometerCountDown(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            notificationBuilder = notificationBuilder.setColor(getResources().getColor(R.color.colorPrimary));
        }
        // adding separate cases for both service types to ensure the order of the action
        // buttons is preserved in the notification
        switch(currentlyRunningServiceType) {
            case 0:
                notificationBuilder.addAction(R.drawable.complete, "Complete", completeActionPendingIntent).addAction(R.drawable.cancel, "Cancel", cancelActionPendingIntent).setContentreplacedle("Tametu Countdown Timer").setContentText(getContentText());
                break;
            case 1:
            case 2:
                notificationBuilder.addAction(R.drawable.cancel, "Cancel", cancelActionPendingIntent).setContentreplacedle("On a break").setContentText("Break timer is running");
                break;
        }
        Notification notification = notificationBuilder.build();
        // Clearing any previous notifications.
        NotificationManagerCompat.from(this).cancel(TASK_INFORMATION_NOTIFICATION_ID);
        startForeground(ID, notification);
        countDownTimerBuilder(TIME_PERIOD, TIME_INTERVAL).start();
        return START_REDELIVER_INTENT;
    }

    private String getContentText() {
        String contentText;
        String taskMessage = preferences.getString(TASK_MESSAGE, null);
        replacedert taskMessage != null;
        if (!taskMessage.equals("")) {
            contentText = taskMessage + " is running";
        } else {
            contentText = "Countdown timer is running";
        }
        return contentText;
    }

    /**
     * @return a CountDownTimer which ticks every 1 second for given Time period.
     */
    private CountDownTimer countDownTimerBuilder(long TIME_PERIOD, long TIME_INTERVAL) {
        currentlyRunningServiceType = Utils.retrieveCurrentlyRunningServiceType(preferences, getApplicationContext());
        countDownTimer = new CountDownTimer(TIME_PERIOD, TIME_INTERVAL) {

            @Override
            public void onTick(long timeInMilliSeconds) {
                soundPool.play(tickID, floatTickingVolumeLevel, floatTickingVolumeLevel, 1, 0, 1f);
                String countDown = Utils.getCurrentDurationPreferenceStringFor(timeInMilliSeconds);
                broadcaster.sendBroadcast(new Intent(COUNTDOWN_BROADCAST).putExtra("countDown", countDown));
            }

            @Override
            public void onFinish() {
                // Updates and Retrieves new value of WorkSessionCount.
                if (currentlyRunningServiceType == TAMETU) {
                    newWorkSessionCount = Utils.updateWorkSessionCount(preferences, getApplicationContext());
                    // Getting type of break user should take, and updating type of currently running service
                    currentlyRunningServiceType = Utils.getTypeOfBreak(preferences, getApplicationContext());
                } else {
                    // If last value of currentlyRunningServiceType was SHORT_BREAK or LONG_BREAK then set it back to POMODORO
                    currentlyRunningServiceType = TAMETU;
                }
                newWorkSessionCount = preferences.getInt(getString(R.string.work_session_count_key), 0);
                // Updating value of currentlyRunningServiceType in SharedPreferences.
                Utils.updateCurrentlyRunningServiceType(preferences, getApplicationContext(), currentlyRunningServiceType);
                // Ring once ticking ends.
                soundPool.play(ringID, floatRingingVolumeLevel, floatRingingVolumeLevel, 2, 0, 1f);
                stopSelf();
                stoppedBroadcastIntent();
            }
        };
        return countDownTimer;
    }

    // Broadcasts intent that the timer has stopped.
    protected void stoppedBroadcastIntent() {
        broadcaster.sendBroadcast(new Intent(STOP_ACTION_BROADCAST).putExtra("workSessionCount", newWorkSessionCount));
    }
}

19 Source : TimerService.java
with Apache License 2.0
from google

/**
 * A {@link Service} to be bound to that exposes a timer.
 */
public clreplaced TimerService extends Service {

    static final String TIMER_ACTION = String.format("%s.TIMER_UPDATE", TimerService.clreplaced.getPackage().getName());

    static final String EXTRA_KEY_TYPE = "type";

    static final String EXTRA_KEY_UPDATE_REMAINING = "remaining";

    static final byte TYPE_UNKNOWN = -1;

    static final byte TYPE_UPDATE = 0;

    static final byte TYPE_FINISH = 1;

    static final int NOTIFICATION_ID = 7777;

    private final IBinder mBinder = new TimerBinder();

    private CountDownTimer mCountDownTimer;

    private boolean mTimerStarted;

    /**
     * Handles response from {@link TimerFragment}
     */
    public interface TimerListener {

        /**
         * Process a {@link TimerValues} result
         *
         * @param values The set {@link TimerValues}
         */
        public void processTimerValues(TimerValues values);
    }

    /**
     * A {@link Binder} that exposes a {@link TimerService}.
     */
    public clreplaced TimerBinder extends Binder {

        TimerService getService() {
            return TimerService.this;
        }
    }

    @Override
    public void onCreate() {
        mTimerStarted = false;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Notification notification = new Notification();
        startForeground(NOTIFICATION_ID, notification);
        return mBinder;
    }

    @Override
    public void onDestroy() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        mTimerStarted = false;
    }

    void setTimer(TimerValues values) {
        // Only allow setting when not already running
        if (!mTimerStarted) {
            mCountDownTimer = new CountDownTimer(values.getTotalMilliseconds(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS)) {

                /* countDownInterval */
                @Override
                public void onTick(long millisUntilFinished) {
                    Intent broadcast = new Intent(TIMER_ACTION);
                    broadcast.putExtra(EXTRA_KEY_TYPE, TYPE_UPDATE);
                    broadcast.putExtra(EXTRA_KEY_UPDATE_REMAINING, millisUntilFinished);
                    LocalBroadcastManager.getInstance(TimerService.this).sendBroadcast(broadcast);
                }

                @Override
                public void onFinish() {
                    mTimerStarted = false;
                    Intent broadcast = new Intent(TIMER_ACTION);
                    broadcast.putExtra(EXTRA_KEY_TYPE, TYPE_FINISH);
                    LocalBroadcastManager.getInstance(TimerService.this).sendBroadcast(broadcast);
                }
            };
        }
    }

    void startTimer() {
        if ((mCountDownTimer != null) && !mTimerStarted) {
            mCountDownTimer.start();
            mTimerStarted = true;
        }
    }

    void stopTimer() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mTimerStarted = false;
        }
    }
}

19 Source : ObjectConfirmationController.java
with Apache License 2.0
from FirebaseExtended

/**
 * Controls the progress of object confirmation before performing additional operation on the
 * detected object.
 */
clreplaced ObjectConfirmationController {

    private final CountDownTimer countDownTimer;

    @Nullable
    private Integer objectId = null;

    private float progress = 0;

    /**
     * @param graphicOverlay Used to refresh camera overlay when the confirmation progress updates.
     */
    ObjectConfirmationController(GraphicOverlay graphicOverlay) {
        long confirmationTimeMs = PreferenceUtils.getConfirmationTimeMs(graphicOverlay.getContext());
        countDownTimer = new CountDownTimer(confirmationTimeMs, /* countDownInterval= */
        20) {

            @Override
            public void onTick(long millisUntilFinished) {
                progress = (float) (confirmationTimeMs - millisUntilFinished) / confirmationTimeMs;
                graphicOverlay.invalidate();
            }

            @Override
            public void onFinish() {
                progress = 1;
            }
        };
    }

    void confirming(Integer objectId) {
        if (objectId.equals(this.objectId)) {
            // Do nothing if it's already in confirming.
            return;
        }
        reset();
        this.objectId = objectId;
        countDownTimer.start();
    }

    boolean isConfirmed() {
        return Float.compare(progress, 1) == 0;
    }

    void reset() {
        countDownTimer.cancel();
        objectId = null;
        progress = 0;
    }

    /**
     * Returns the confirmation progress described as a float value in the range of [0, 1].
     */
    float getProgress() {
        return progress;
    }
}

19 Source : RenewableTimer.java
with Apache License 2.0
from firebase

/**
 * Countdown timers cannot be renewed and need to be repeated created for each usage making it hard
 * to test without a factory. This timer encapsulates what could have been a factory
 *
 * <p>Callers are expected to cancel timers before starting new ones, failing which the strong
 * callback references could lead to memory leaks
 *
 * @hide
 */
public clreplaced RenewableTimer {

    private CountDownTimer mCountDownTimer;

    @Inject
    RenewableTimer() {
    }

    public void start(final Callback c, long duration, long interval) {
        mCountDownTimer = new CountDownTimer(duration, interval) {

            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                c.onFinish();
            }
        }.start();
    }

    public void cancel() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    public interface Callback {

        void onFinish();
    }
}

19 Source : FloatWaitView.java
with Apache License 2.0
from Demidong

/**
 * Created by demi on 2019/2/18 下午5:42.
 */
public clreplaced FloatWaitView extends View {

    private int ovalNum = 4;

    // 圆球颜色
    private int color;

    // 圆球从底部浮动到顶部的时长
    private int duration;

    // 圆球之间的间隔
    private float wideSpace;

    // 圆球浮动高度
    private float floatHight;

    public float radius;

    public int bg;

    public boolean ovalCenter;

    private Paint mPaint;

    private CountDownTimer timer;

    private ArrayList<Oval> mOvals = new ArrayList<>();

    int position = 0;

    private boolean isUserStop = false;

    private boolean isMoving = false;

    public FloatWaitView(Context context) {
        this(context, null);
    }

    public FloatWaitView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FloatWaitView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatWaitView);
        color = a.getColor(R.styleable.FloatWaitView_fwv_color, Color.RED);
        floatHight = a.getDimension(R.styleable.FloatWaitView_fwv_floatHight, 40);
        wideSpace = a.getDimension(R.styleable.FloatWaitView_fwv_wideSpace, 40);
        radius = a.getDimension(R.styleable.FloatWaitView_fwv_radius, 20);
        ovalNum = a.getInteger(R.styleable.FloatWaitView_fwv_ovalNum, 4);
        bg = a.getInteger(R.styleable.FloatWaitView_fwv_bg, Color.TRANSPARENT);
        duration = a.getInteger(R.styleable.FloatWaitView_fwv_duration, 800);
        ovalCenter = a.getBoolean(R.styleable.FloatWaitView_fwv_ovalInHorizontalCenter, true);
        a.recycle();
        init();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 调用时刻:onCreate之后onDraw之前调用;view的大小发生改变就会调用该方法
        int measuredWidth = getMeasuredWidth();
        for (int i = 0; i < ovalNum; i++) {
            Oval oval = mOvals.get(i);
            if (ovalCenter)
                oval.x = (measuredWidth - (wideSpace + 2 * radius) * ovalNum) / 2 + (wideSpace / 2 + radius) * (2 * i + 1);
            else
                oval.x = getPaddingLeft() + (wideSpace / 2 + radius) * (2 * i + 1);
            oval.y = floatHight - radius;
        }
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);
        for (int i = 0; i < ovalNum; i++) {
            Oval oval = new Oval();
            oval.mAnimator = createFloatAnimation(i);
            mOvals.add(oval);
        }
    }

    private void createTimer() {
        timer = new CountDownTimer(duration, duration / (ovalNum + 1)) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (position < ovalNum) {
                    Oval oval = mOvals.get(position++);
                    oval.mAnimator.start();
                }
            }

            @Override
            public void onFinish() {
            }
        };
        timer.start();
    }

    public void startMoving() {
        if (isMoving || getVisibility() == INVISIBLE) {
            return;
        }
        isMoving = true;
        isUserStop = false;
        createTimer();
    }

    public void stopMoving() {
        isUserStop = true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(bg);
        canvas.translate(0, getHeight() / 2 - floatHight / 2);
        canvas.drawRect(0, 0, getWidth(), floatHight, mPaint);
        mPaint.setColor(color);
        for (int i = 0; i < ovalNum; i++) {
            Oval oval = mOvals.get(i);
            canvas.drawCircle(oval.x, oval.y, radius, mPaint);
        }
    }

    private ValueAnimator createFloatAnimation(final int pos) {
        ValueAnimator animator = ValueAnimator.ofFloat(floatHight - radius, radius, floatHight - radius);
        animator.setDuration(duration);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Oval oval = mOvals.get(pos);
                if (ovalCenter)
                    oval.x = (getWidth() - (wideSpace + 2 * radius) * ovalNum) / 2 + (wideSpace / 2 + radius) * (2 * pos + 1);
                else
                    oval.x = getPaddingLeft() + (wideSpace / 2 + radius) * (2 * pos + 1);
                oval.y = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (pos == ovalNum - 1) {
                    isMoving = false;
                    position = 0;
                    if (!isUserStop) {
                        createTimer();
                    }
                }
            }
        });
        return animator;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int resultWideSize, resultWideMode, resultHighSize, resultHighMode;
        int wideMode = MeasureSpec.getMode(widthMeasureSpec);
        int wideSize = MeasureSpec.getSize(widthMeasureSpec);
        int highMode = MeasureSpec.getMode(heightMeasureSpec);
        int highSize = MeasureSpec.getSize(heightMeasureSpec);
        if (wideMode == MeasureSpec.EXACTLY) {
            resultWideMode = MeasureSpec.EXACTLY;
            resultWideSize = wideSize + getPaddingLeft() + getPaddingRight();
        } else {
            resultWideMode = MeasureSpec.AT_MOST;
            resultWideSize = (int) ((wideSpace + 2 * radius) * ovalNum) + getPaddingLeft() + getPaddingRight();
        }
        if (highMode == MeasureSpec.EXACTLY) {
            resultHighMode = MeasureSpec.EXACTLY;
            resultHighSize = highSize + getPaddingTop() + getPaddingBottom();
        } else {
            resultHighMode = MeasureSpec.AT_MOST;
            resultHighSize = (int) (floatHight + getPaddingTop() + getPaddingBottom());
        }
        setMeasuredDimension(MeasureSpec.makeMeasureSpec(resultWideSize, resultWideMode), MeasureSpec.makeMeasureSpec(resultHighSize, resultHighMode));
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isUserStop = true;
        if (timer != null) {
            timer.cancel();
        }
        for (int i = 0; i < mOvals.size(); i++) {
            mOvals.get(i).mAnimator.cancel();
            mOvals.get(i).mAnimator.removeAllUpdateListeners();
        }
        mOvals.clear();
    }

    clreplaced Oval {

        // 圆心 x坐标
        public float x;

        // 圆心 y坐标
        public float y;

        // 动画
        public ValueAnimator mAnimator;
    }
}

19 Source : FloatLoadingView.java
with Apache License 2.0
from Demidong

/**
 * Created by demi on 2019/2/18 下午5:42.
 */
public clreplaced FloatLoadingView extends View {

    private int ovalNum = 4;

    // 圆球颜色
    private int color;

    // 圆球从底部浮动到顶部的时长
    private int duration;

    // 圆球之间的间隔
    private float wideSpace;

    // 圆球浮动高度
    private float floatHight;

    public float radius;

    public boolean ovalCenter;

    private Paint mPaint;

    private CountDownTimer timer;

    private FixedOval[] mOvals;

    private MoveOval mMoveOval;

    int currentPosition = 0;

    private ValueAnimator valueAnimator;

    private boolean isMoving;

    private boolean isUserStop;

    public FloatLoadingView(Context context) {
        this(context, null);
    }

    public FloatLoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FloatLoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FloatLoadingView);
        color = a.getColor(R.styleable.FloatLoadingView_flv_color, Color.RED);
        floatHight = a.getDimension(R.styleable.FloatLoadingView_flv_floatHight, 40);
        wideSpace = a.getDimension(R.styleable.FloatLoadingView_flv_wideSpace, 40);
        radius = a.getDimension(R.styleable.FloatLoadingView_flv_radius, 20);
        ovalNum = a.getInteger(R.styleable.FloatLoadingView_flv_ovalNum, 4);
        duration = a.getInteger(R.styleable.FloatLoadingView_flv_duration, 800);
        ovalCenter = a.getBoolean(R.styleable.FloatLoadingView_flv_ovalInHorizontalCenter, true);
        a.recycle();
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        initOval();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 调用时刻:onCreate之后onDraw之前调用;view的大小发生改变就会调用该方法
        for (int i = 0; i < ovalNum; i++) {
            float x = (getMeasuredWidth() - (wideSpace + 2 * radius) * ovalNum) / 2 + radius;
            float y = floatHight - radius;
            if (i == 0) {
                mOvals[i].point.set(x, y);
            } else {
                mOvals[i].point.set(mOvals[i - 1].point);
                mOvals[i].point.offset(2 * radius + wideSpace, 0);
            }
        }
        mMoveOval.point.set(mOvals[currentPosition].point);
    }

    private void initOval() {
        mOvals = new FixedOval[ovalNum];
        for (int i = 0; i < ovalNum; i++) {
            mOvals[i] = new FixedOval();
            mOvals[i].index = i;
            mOvals[i].point = new PointF();
            mOvals[i].isShow = true;
        }
        mMoveOval = new MoveOval();
        mMoveOval.index = currentPosition;
        mMoveOval.point = new PointF();
        relate_Oval(mOvals);
    }

    private void relate_Oval(FixedOval[] ovals) {
        for (int i = 0; i < ovalNum; i++) {
            if (i == ovalNum - 1) {
                ovals[i].next = mOvals[0];
            } else {
                ovals[i].next = mOvals[i + 1];
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(0, getHeight() / 2 - floatHight / 2);
        mPaint.setColor(color);
        for (int i = 0; i < ovalNum; i++) {
            FixedOval oval = mOvals[i];
            if (oval.isShow) {
                canvas.drawCircle(oval.point.x, oval.point.y, radius, mPaint);
            }
        }
        canvas.drawCircle(mMoveOval.point.x, mMoveOval.point.y, radius, mPaint);
    }

    private void createFloatAnimator() {
        valueAnimator = ValueAnimator.ofFloat(floatHight - radius, radius, floatHight - radius);
        valueAnimator.setDuration(duration);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mMoveOval.point.y = value;
                invalidate();
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                mMoveOval.point.set(mOvals[currentPosition].point);
                mMoveOval.index = mOvals[currentPosition].index;
                mOvals[currentPosition].isShow = false;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isMoving = false;
                mOvals[currentPosition].isShow = true;
                currentPosition = mOvals[currentPosition].next.index;
                if (!isUserStop) {
                    startMoving();
                }
            }
        });
        valueAnimator.start();
    }

    public void startMoving() {
        if (isMoving || getVisibility() == INVISIBLE) {
            return;
        }
        isMoving = true;
        isUserStop = false;
        createFloatAnimator();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int resultWideSize, resultWideMode, resultHighSize, resultHighMode;
        int wideMode = MeasureSpec.getMode(widthMeasureSpec);
        int wideSize = MeasureSpec.getSize(widthMeasureSpec);
        int highMode = MeasureSpec.getMode(heightMeasureSpec);
        int highSize = MeasureSpec.getSize(heightMeasureSpec);
        if (wideMode == MeasureSpec.EXACTLY) {
            resultWideMode = MeasureSpec.EXACTLY;
            resultWideSize = wideSize + getPaddingLeft() + getPaddingRight();
        } else {
            resultWideMode = MeasureSpec.AT_MOST;
            resultWideSize = (int) ((wideSpace + 2 * radius) * ovalNum) + getPaddingLeft() + getPaddingRight();
        }
        if (highMode == MeasureSpec.EXACTLY) {
            resultHighMode = MeasureSpec.EXACTLY;
            resultHighSize = highSize + getPaddingTop() + getPaddingBottom();
        } else {
            resultHighMode = MeasureSpec.AT_MOST;
            resultHighSize = (int) (floatHight + getPaddingTop() + getPaddingBottom());
        }
        setMeasuredDimension(MeasureSpec.makeMeasureSpec(resultWideSize, resultWideMode), MeasureSpec.makeMeasureSpec(resultHighSize, resultHighMode));
    }

    public void stopMoving() {
        isUserStop = true;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (valueAnimator != null) {
            valueAnimator.removeAllUpdateListeners();
            valueAnimator.cancel();
        }
    }

    private clreplaced MoveOval {

        PointF point;

        int index;
    }

    private clreplaced FixedOval {

        PointF point;

        int index;

        FixedOval next;

        boolean isShow;
    }
}

19 Source : SosActivity.java
with GNU General Public License v3.0
from COMP30022-18

public clreplaced SosActivity extends AppCompatActivity {

    private CountDownTimer countDownTimer;

    private CircularProgressView countDownView;

    private TextView countDownText;

    private FusedLocationProviderClient mFusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sos);
        // If activity is called by fall detection
        boolean isDetected = getIntent().getBooleanExtra("fall_detection", false);
        if (isDetected) {
            TextView textView = findViewById(R.id.sos_countdown_pre_text);
            textView.setText(R.string.sos_pre_text);
        }
        checkPhoneCallPermission();
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        countDownView = findViewById(R.id.sos_progress);
        countDownText = findViewById(R.id.sos_progress_text);
        countDownView.setMax(10 * 1000);
        countDownView.setProgress(10 * 1000);
        countDownView.setAnimationInterpolator(new LinearInterpolator());
        countDownTimer = new CountDownTimer(10 * 1000, 1000) {

            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long l) {
                countDownText.setText(Long.toString(l / 1000 + 1));
                countDownView.setProgress(l, true, 1000);
            }

            @Override
            public void onFinish() {
                triggerSOS();
            }
        };
        countDownTimer.start();
    }

    public void notifyOnClick(View view) {
        countDownTimer.cancel();
        triggerSOS();
    }

    public void cancelOnClick(View view) {
        cancel();
    }

    @Override
    public void onBackPressed() {
        cancel();
    }

    private void cancel() {
        countDownTimer.cancel();
        finish();
    }

    private void triggerSOS() {
        String phoneNumber = androidx.preference.PreferenceManager.getDefaultSharedPreferences(this).getString("sos_emergency_call", "");
        String contactUid = androidx.preference.PreferenceManager.getDefaultSharedPreferences(this).getString("sos_emergency_contact", "");
        PrivateConversation conv = ConversationManager.getInstance().getPrivateConversation(contactUid);
        if (conv != null) {
            // emergency message
            conv.sendMessage("text", getString(R.string.sos_emergency_message));
            // location
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, getString(R.string.sos_emergency_no_location), Toast.LENGTH_LONG).show();
                } else {
                    mFusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
                        if (location != null) {
                            conv.sendLocation(location.getLareplacedude(), location.getLongitude());
                            Toast.makeText(this, getString(R.string.sos_emergency_sent_location), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }
        // check digit only
        if ((!phoneNumber.isEmpty() && !android.text.TextUtils.isDigitsOnly(phoneNumber)) || phoneNumber.isEmpty()) {
            Toast.makeText(this, getString(R.string.sos_emergency_phone), Toast.LENGTH_SHORT).show();
        } else {
            // emergency phone call
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + phoneNumber));
            callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, getString(R.string.sos_emergency_no_number), Toast.LENGTH_LONG).show();
            } else {
                startActivity(callIntent);
            }
        }
        finish();
    }

    // Check the phone call permission
    public void checkPhoneCallPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CALL_PHONE }, 1);
        }
    }
}

19 Source : DrawTextActivity.java
with Apache License 2.0
from ChillingVan

public clreplaced DrawTextActivity extends AppCompatActivity {

    private MediaPlayerHelper mediaPlayer = new MediaPlayerHelper();

    private Surface mediaSurface;

    private DrawTextTextureView drawTextTextureView;

    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw_text);
        initTextureView();
    }

    private void initTextureView() {
        drawTextTextureView = findViewById(R.id.media_player_texture_view);
        final TextView frameRateTxt = findViewById(R.id.frame_rate_txt);
        drawTextTextureView.setOnSurfaceTextureSet(new GLSurfaceTextureProducerView.OnSurfaceTextureSet() {

            @Override
            public void onSet(SurfaceTexture surfaceTexture, RawTexture surfaceTextureRelatedTexture) {
                // No need to request draw because it is continues GL View.
                mediaSurface = new Surface(surfaceTexture);
            }
        });
        countDownTimer = new CountDownTimer(1000 * 3600, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                frameRateTxt.setText(String.valueOf(drawTextTextureView.getFrameRate()));
            }

            @Override
            public void onFinish() {
            }
        };
        countDownTimer.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        drawTextTextureView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        drawTextTextureView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        countDownTimer.cancel();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.release();
        }
    }

    public void onClickStart(View view) {
        if ((mediaPlayer.isPlaying() || mediaPlayer.isLooping())) {
            return;
        }
        playMedia();
    }

    private void playMedia() {
        mediaPlayer.playMedia(this, mediaSurface);
        drawTextTextureView.start();
    }
}

19 Source : QuizViewModel.java
with MIT License
from bundeeteddee

/**
 * Created by bundee on 9/14/16.
 */
public clreplaced QuizViewModel extends BaseObservable implements ViewModel, Parcelable {

    // Tag
    private static final String TAG = QuizViewModel.clreplaced.getName();

    // Time out, in sec
    private static final int QUIZ_TIMEOUT = 10;

    // Variables
    private Quiz mQuiz;

    private boolean mChoicesDisabled;

    private CountDownTimer mTimer;

    @Bindable
    private int mCountDownTime;

    /**
     * Default constructor
     * @param quiz
     */
    public QuizViewModel(Quiz quiz) {
        this.mQuiz = quiz;
        this.mChoicesDisabled = false;
        if (mQuiz.getChosen() == null) {
            if (mTimer == null) {
                this.mCountDownTime = QUIZ_TIMEOUT;
                mTimer = new CountDownTimer(QUIZ_TIMEOUT * 1000, 800) {

                    public void onTick(long millisUntilFinished) {
                        mCountDownTime = Math.round(millisUntilFinished / 1000f);
                        notifyPropertyChanged(BR.countDownTime);
                    }

                    public void onFinish() {
                        mChoicesDisabled = true;
                        mCountDownTime = 0;
                        mQuiz.setChosen(new Choice());
                        notifyChange();
                    }
                }.start();
            }
        } else {
            this.mCountDownTime = 0;
        }
    }

    protected QuizViewModel(Parcel in) {
        mQuiz = in.readParcelable(Quiz.clreplaced.getClreplacedLoader());
        mChoicesDisabled = in.readByte() != 0;
        mCountDownTime = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(mQuiz, flags);
        dest.writeByte((byte) (mChoicesDisabled ? 1 : 0));
        dest.writeInt(mCountDownTime);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<QuizViewModel> CREATOR = new Creator<QuizViewModel>() {

        @Override
        public QuizViewModel createFromParcel(Parcel in) {
            return new QuizViewModel(in);
        }

        @Override
        public QuizViewModel[] newArray(int size) {
            return new QuizViewModel[size];
        }
    };

    public Quiz getQuiz() {
        return mQuiz;
    }

    public boolean getChoicesDisabled() {
        return mChoicesDisabled;
    }

    public Choice getFirstChoice() {
        return mQuiz.getChoices().get(0);
    }

    public Choice getSecondChoice() {
        return mQuiz.getChoices().get(1);
    }

    public Choice getThirdChoice() {
        return mQuiz.getChoices().get(2);
    }

    public Choice getFourthChoice() {
        return mQuiz.getChoices().get(3);
    }

    public Choice getFifthChoice() {
        return mQuiz.getChoices().get(4);
    }

    public String getCountDownTime() {
        return mCountDownTime + "s";
    }

    /**
     * on click for selecting a choice
     */
    public void onChoiceClicked(View v) {
        mChoicesDisabled = true;
        mTimer.cancel();
        mCountDownTime = 0;
        if (v.getTag() != null) {
            mQuiz.setChosen((Choice) v.getTag());
            notifyChange();
        }
    }

    /**
     * On click for done close button
     * @param v
     */
    public void onCloseQuizClicked(View v) {
        EventBus.getDefault().post(new CloseQuizEvent());
    }

    /**
     * On click for next quiz
     */
    public void onNextQuizClicked(View v) {
        EventBus.getDefault().post(new NextQuizEvent());
    }

    public int getBackgroundColor(Choice currentChoice) {
        if (mQuiz.getChosen() != null) {
            if (mQuiz.getChosen().equals(currentChoice)) {
                if (currentChoice.getIsTheCorrectAnswer()) {
                    return ResourceUtil.GetColor(R.color.button_quiz_choice_correct);
                } else {
                    return ResourceUtil.GetColor(R.color.button_quiz_choice_wrong);
                }
            }
            if (currentChoice.getIsTheCorrectAnswer()) {
                return ResourceUtil.GetColor(R.color.button_quiz_choice_correct);
            }
        }
        return ResourceUtil.GetColor(R.color.button_quiz_choice_default);
    }

    public int getNextButtonVisibility() {
        return mQuiz.getChosen() != null ? View.VISIBLE : View.GONE;
    }

    public int getCountDownVisibility() {
        return mCountDownTime == 0 ? View.GONE : View.VISIBLE;
    }

    public boolean getChoiceMarginSelected(Choice currentChoice) {
        if (mQuiz.getChosen() != null && mQuiz.getChosen().equals(currentChoice)) {
            return true;
        }
        return false;
    }

    public boolean getNextButtonVisible() {
        return getNextButtonVisibility() == View.VISIBLE;
    }

    @BindingAdapter("fadeVisible")
    public static void setFadeVisible(final View view, boolean visible) {
        if (view.getTag() == null) {
            view.setTag(true);
            view.setVisibility(visible ? View.VISIBLE : View.GONE);
        } else {
            view.animate().cancel();
            if (visible) {
                view.setVisibility(View.VISIBLE);
                view.setAlpha(0);
                view.animate().alpha(1).setListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        view.setAlpha(1);
                    }
                });
            } else {
                view.animate().alpha(0).setListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        view.setAlpha(1);
                        view.setVisibility(View.GONE);
                    }
                });
            }
        }
    }

    public int getResultIcon() {
        if (mQuiz.getChosen() != null && mQuiz.getChosen().getIsTheCorrectAnswer()) {
            return R.drawable.ico_correct;
        }
        return R.drawable.ico_wrong;
    }

    @BindingAdapter("resultIcon")
    public static void setResultIcon(ImageView view, @DrawableRes int resId) {
        view.setImageResource(resId);
    }

    @Override
    public void destroy() {
        // TODO: clean up any other subscribers
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}

19 Source : SplashActivity.java
with Apache License 2.0
from brokes6

/**
 * 启动页
 */
public clreplaced SplashActivity extends BaseActivity {

    private static final String TAG = "SplashActivity";

    private CountDownTimer countDownTimer;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(R.layout.activity_splash);
    }

    @Override
    protected BasePresenter onCreatePresenter() {
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        ScreenUtils.setStatusBarColor(this, Color.parseColor("#Db2C1F"));
    }

    @Override
    protected void initData() {
        startCountDownTime();
    }

    @Override
    protected void initView() {
    }

    private void startCountDownTime() {
        countDownTimer = new CountDownTimer(2000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                String authToken = SharePreferenceUtil.getInstance(SplashActivity.this).getAuthToken("");
                if (TextUtils.isEmpty(authToken)) {
                    ActivityStarter.getInstance().startLoginActivity(SplashActivity.this);
                } else {
                    ActivityStarter.getInstance().startMainActivity(SplashActivity.this);
                }
                SplashActivity.this.finish();
            }
        };
        countDownTimer.start();
    }

    @Override
    public void onBackPressed() {
    // super.onBackPressed();
    }

    @Override
    public void finish() {
        super.finish();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    @Override
    public void onClick(View v) {
    }
}

19 Source : AsynchronousBackgroundHandler.java
with MIT License
from BioID-GmbH

@Override
public void cancelScheduledTask(int taskId) {
    CountDownTimer scheduledTask = scheduledTasks.remove(taskId);
    if (scheduledTask != null) {
        scheduledTask.cancel();
    }
}

19 Source : AsynchronousBackgroundHandler.java
with MIT License
from BioID-GmbH

@Override
public int runWithDelay(@NonNull final Runnable runnable, @IntRange(from = 0) long delayInMillis) {
    final int taskId = getTaskId(scheduledTasks);
    CountDownTimer scheduledTask = new CountDownTimer(delayInMillis, delayInMillis) {

        @Override
        public void onTick(long l) {
        // do nothing (is disabled anyway because "countDownInterval" is set to "millisInFuture")
        }

        @Override
        public void onFinish() {
            scheduledTasks.remove(taskId);
            runnable.run();
        }
    }.start();
    scheduledTasks.put(taskId, scheduledTask);
    return taskId;
}

19 Source : StartActivity.java
with Apache License 2.0
from beanu

/**
 * 启动页
 */
public clreplaced StartActivity extends AppCompatActivity {

    private View mContentView;

    private ImageView mImgAd;

    private Button mBtnJump;

    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置状态栏透明状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        // 设置状态栏透明状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_start);
        if (getSupportActionBar() != null)
            getSupportActionBar().hide();
        // 查找View
        mContentView = findViewById(R.id.fullscreen_content);
        mImgAd = findViewById(R.id.img_splash_ad);
        mBtnJump = findViewById(R.id.btn_jump_over);
        // 执行行为
        Observable.merge(tryLogin(), initConfig(), playLogoAnim()).subscribe(new Observer<Object>() {

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Object o) {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                if (!TextUtils.isEmpty(AppHolder.getInstance().mConfig.getAdImg())) {
                    Glide.with(StartActivity.this).load(AppHolder.getInstance().mConfig.getAdImg()).into(mImgAd);
                    mBtnJump.setVisibility(View.VISIBLE);
                    startCountDown(3000);
                } else {
                    mImgAd.setVisibility(View.GONE);
                    gotoNextPage();
                }
            }
        });
    }

    // logo动画
    private Observable<Object> playLogoAnim() {
        return Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(final ObservableEmitter<Object> e) throws Exception {
                ObjectAnimator anim = ObjectAnimator.ofFloat(mContentView, "alpha", 0, 1);
                anim.setDuration(2000);
                anim.start();
                anim.addListener(new Animator.AnimatorListener() {

                    @Override
                    public void onAnimationStart(Animator animator) {
                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        e.onComplete();
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {
                    }
                });
                e.onNext(new Object());
            }
        });
    }

    // 进入下一页
    private void gotoNextPage() {
        boolean isFirst = Arad.preferences.getBoolean(Constants.P_ISFIRSTLOAD, true);
        if (!isFirst) {
            Intent intent = new Intent(StartActivity.this, MainActivity.clreplaced);
            startActivity(intent);
        } else {
            Intent intent = new Intent(StartActivity.this, MainActivity.clreplaced);
            startActivity(intent);
        }
        finish();
        overridePendingTransition(R.anim.fade, R.anim.hold);
    }

    private void startCountDown(long millisInFuture) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        countDownTimer = new CountDownTimer(millisInFuture + 500, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mBtnJump.setText(String.format(Locale.CHINA, "%ds跳过", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                mBtnJump.setText(R.string.jump_over_0s);
                gotoNextPage();
            }
        }.start();
    }

    // 自动登录
    private Observable<Object> tryLogin() {
        String phone = Arad.preferences.getString(Constants.P_ACCOUNT);
        String preplacedword = Arad.preferences.getString(Constants.P_PWD);
        String loginType = Arad.preferences.getString(Constants.P_LOGIN_TYPE);
        String loginOpenId = Arad.preferences.getString(Constants.P_LOGIN_OPENID);
        if ("0".equals(loginType)) {
            // 密码登录
            preplacedword = ConvertUtils.bytes2HexString(EncryptUtils.decryptHexStringDES(preplacedword, Constants.DES_KEY));
        }
        return API.getInstance(APIService.clreplaced).login(loginType, phone, preplacedword).compose(RxHelper.<User>handleResult()).map(new Function<User, Object>() {

            @Override
            public Object apply(User user) throws Exception {
                // AppHolder.getInstance().setUser(user);
                return AppHolder.getInstance().user;
            }
        }).onErrorReturnItem(AppHolder.getInstance().user);
    }

    // 获取自动配置
    private Observable<Object> initConfig() {
        return API.getInstance(APIService.clreplaced).getConfig().compose(RxHelper.<GlobalConfig>handleResult()).map(new Function<GlobalConfig, Object>() {

            @Override
            public Object apply(GlobalConfig globalConfig) throws Exception {
                // AppHolder.getInstance().setConfig(globalConfig);
                return AppHolder.getInstance().mConfig;
            }
        }).onErrorReturnItem(AppHolder.getInstance().mConfig);
    }
}

19 Source : SubmitButtonActivity.java
with Apache License 2.0
from arjinmc

/**
 * Created by Eminem Lo on 27/3/17.
 * Email [email protected]
 */
public clreplaced SubmitButtonActivity extends AppCompatActivity {

    private SubmitButton submitButton;

    private Button btnForceError;

    private CountDownTimer countDownTimer = new CountDownTimer(6000, 500) {

        @Override
        public void onTick(long millisUntilFinished) {
            submitButton.setProgress((int) ((6000 - millisUntilFinished) / 500) * 10);
        }

        @Override
        public void onFinish() {
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submitbutton);
        submitButton = (SubmitButton) findViewById(R.id.btn_submit);
        submitButton.setOnSubmitListener(new SubmitButton.OnSubmitListener() {

            @Override
            public void onReady() {
                // here to call request
                countDownTimer.start();
            }

            @Override
            public void onSignalFinsh() {
            }
        });
        btnForceError = (Button) findViewById(R.id.btn_force_error);
        btnForceError.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                countDownTimer.cancel();
                submitButton.setErrorStatus();
            }
        });
    }
}

19 Source : DownloadButtonActivity.java
with Apache License 2.0
from arjinmc

public clreplaced DownloadButtonActivity extends AppCompatActivity {

    private DownloadButton downloadButton;

    private Button btnReset;

    private CountDownTimer timer = new CountDownTimer(50000, 500) {

        @Override
        public void onTick(long millisUntilFinished) {
            // virtual progress
            if (downloadButton != null)
                downloadButton.setProgress(100 - (int) (millisUntilFinished / 500));
        // Log.e("downloadButton","progress:"+downloadButton.getmProgress());
        }

        @Override
        public void onFinish() {
            downloadButton.setProgress(100);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_downloadbutton);
        downloadButton = (DownloadButton) findViewById(R.id.btn_download);
        downloadButton.setOnDownloadListener(new DownloadButton.OnDownloadListener() {

            @Override
            public void onReady() {
                // call request on this method
                timer.start();
            }

            @Override
            public void onDone() {
                // finish the done animation will callback this method
                Log.e("onDone", "done");
            }
        });
        btnReset = (Button) findViewById(R.id.btn_reset);
        btnReset.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                downloadButton.reset();
                timer.cancel();
            }
        });
    }
}

19 Source : GoogleAdActivity.java
with Apache License 2.0
from AriesHoo

/**
 * Main Activity. Inflates main activity xml.
 */
public clreplaced GoogleAdActivity extends AppCompatActivity {

    private static final long GAME_LENGTH_MILLISECONDS = 3000;

    private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712";

    private IntersreplacedialAd intersreplacedialAd;

    private CountDownTimer countDownTimer;

    private Button retryButton;

    private boolean gameIsInProgress;

    private long timerMilliseconds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_ad);
        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(this, new OnInitializationCompleteListener() {

            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        // Create the IntersreplacedialAd and set the adUnitId.
        intersreplacedialAd = new IntersreplacedialAd(this);
        // Defined in res/values/strings.xml
        intersreplacedialAd.setAdUnitId(AD_UNIT_ID);
        intersreplacedialAd.setAdListener(new AdListener() {

            @Override
            public void onAdLoaded() {
                ToastUtil.show("onAdLoaded()");
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                ToastUtil.show("onAdFailedToLoad() with error code: " + errorCode);
            }

            @Override
            public void onAdClosed() {
                startGame();
            }
        });
        // Create the "retry" button, which tries to show an intersreplacedial between game plays.
        retryButton = findViewById(R.id.retry_button);
        retryButton.setVisibility(View.INVISIBLE);
        retryButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                showIntersreplacedial();
            }
        });
        startGame();
    }

    private void createTimer(final long milliseconds) {
        // Create the game timer, which counts down to the end of the level
        // and shows the "retry" button.
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        final TextView textView = findViewById(R.id.timer);
        countDownTimer = new CountDownTimer(milliseconds, 50) {

            @Override
            public void onTick(long millisUnitFinished) {
                timerMilliseconds = millisUnitFinished;
                textView.setText("seconds remaining: " + ((millisUnitFinished / 1000) + 1));
            }

            @Override
            public void onFinish() {
                gameIsInProgress = false;
                textView.setText("done!");
                retryButton.setVisibility(View.VISIBLE);
            }
        };
    }

    @Override
    public void onResume() {
        // Start or resume the game.
        super.onResume();
        if (gameIsInProgress) {
            resumeGame(timerMilliseconds);
        }
    }

    @Override
    public void onPause() {
        // Cancel the timer if the game is paused.
        countDownTimer.cancel();
        super.onPause();
    }

    private void showIntersreplacedial() {
        // Show the ad if it's ready. Otherwise toast and restart the game.
        if (intersreplacedialAd != null && intersreplacedialAd.isLoaded()) {
            intersreplacedialAd.show();
        } else {
            Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
            startGame();
        }
    }

    private void startGame() {
        // Request a new ad if one isn't already loaded, hide the button, and kick off the timer.
        if (!intersreplacedialAd.isLoading() && !intersreplacedialAd.isLoaded()) {
            AdRequest adRequest = new AdRequest.Builder().build();
            intersreplacedialAd.loadAd(adRequest);
        }
        retryButton.setVisibility(View.INVISIBLE);
        resumeGame(GAME_LENGTH_MILLISECONDS);
    }

    private void resumeGame(long milliseconds) {
        // Create a new timer for the correct length and start it.
        gameIsInProgress = true;
        timerMilliseconds = milliseconds;
        createTimer(milliseconds);
        countDownTimer.start();
    }
}

19 Source : MainActivity.java
with Apache License 2.0
from android

/**
 * We first get the required permission to use the MIC. If it is granted, then we continue with
 * the application and present the UI with three icons: a MIC icon (if pressed, user can record up
 * to 10 seconds), a Play icon (if clicked, it wil playback the recorded audio file) and a music
 * note icon (if clicked, it plays an MP3 file that is included in the app).
 */
public clreplaced MainActivity extends FragmentActivity implements AmbientModeSupport.AmbientCallbackProvider, UIAnimation.UIStateListener, SoundRecorder.OnVoicePlaybackStateChangedListener {

    private static final String TAG = "MainActivity";

    private static final int PERMISSIONS_REQUEST_CODE = 100;

    private static final long COUNT_DOWN_MS = TimeUnit.SECONDS.toMillis(10);

    private static final long MILLIS_IN_SECOND = TimeUnit.SECONDS.toMillis(1);

    private static final String VOICE_FILE_NAME = "audiorecord.pcm";

    private MediaPlayer mMediaPlayer;

    private AppState mState = AppState.READY;

    private UIAnimation.UIState mUiState = UIAnimation.UIState.HOME;

    private SoundRecorder mSoundRecorder;

    private RelativeLayout mOuterCircle;

    private View mInnerCircle;

    private UIAnimation mUIAnimation;

    private ProgressBar mProgressBar;

    private CountDownTimer mCountDownTimer;

    /**
     * Ambient mode controller attached to this display. Used by Activity to see if it is in
     * ambient mode.
     */
    private AmbientModeSupport.AmbientController mAmbientController;

    enum AppState {

        READY, PLAYING_VOICE, PLAYING_MUSIC, RECORDING
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        mOuterCircle = findViewById(R.id.outer_circle);
        mInnerCircle = findViewById(R.id.inner_circle);
        mProgressBar = findViewById(R.id.progress_bar);
        // Enables Ambient mode.
        mAmbientController = AmbientModeSupport.attach(this);
    }

    private void setProgressBar(long progressInMillis) {
        mProgressBar.setProgress((int) (progressInMillis / MILLIS_IN_SECOND));
    }

    @Override
    public void onUIStateChanged(UIAnimation.UIState state) {
        Log.d(TAG, "UI State is: " + state);
        if (mUiState == state) {
            return;
        }
        switch(state) {
            case MUSIC_UP:
                mState = AppState.PLAYING_MUSIC;
                mUiState = state;
                playMusic();
                break;
            case MIC_UP:
                mState = AppState.RECORDING;
                mUiState = state;
                mSoundRecorder.startRecording();
                setProgressBar(COUNT_DOWN_MS);
                mCountDownTimer = new CountDownTimer(COUNT_DOWN_MS, MILLIS_IN_SECOND) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                        mProgressBar.setVisibility(View.VISIBLE);
                        setProgressBar(millisUntilFinished);
                        Log.d(TAG, "Time Left: " + millisUntilFinished / MILLIS_IN_SECOND);
                    }

                    @Override
                    public void onFinish() {
                        mProgressBar.setProgress(0);
                        mProgressBar.setVisibility(View.INVISIBLE);
                        mSoundRecorder.stopRecording();
                        mUIAnimation.transitionToHome();
                        mUiState = UIAnimation.UIState.HOME;
                        mState = AppState.READY;
                        mCountDownTimer = null;
                    }
                };
                mCountDownTimer.start();
                break;
            case SOUND_UP:
                mState = AppState.PLAYING_VOICE;
                mUiState = state;
                mSoundRecorder.startPlay();
                break;
            case HOME:
                switch(mState) {
                    case PLAYING_MUSIC:
                        mState = AppState.READY;
                        mUiState = state;
                        stopMusic();
                        break;
                    case PLAYING_VOICE:
                        mState = AppState.READY;
                        mUiState = state;
                        mSoundRecorder.stopPlaying();
                        break;
                    case RECORDING:
                        mState = AppState.READY;
                        mUiState = state;
                        mSoundRecorder.stopRecording();
                        if (mCountDownTimer != null) {
                            mCountDownTimer.cancel();
                            mCountDownTimer = null;
                        }
                        mProgressBar.setVisibility(View.INVISIBLE);
                        setProgressBar(COUNT_DOWN_MS);
                        break;
                }
                break;
        }
    }

    /**
     * Plays back the MP3 file embedded in the application
     */
    private void playMusic() {
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.sound);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // we need to transition to the READY/Home state
                    Log.d(TAG, "Music Finished");
                    mUIAnimation.transitionToHome();
                }
            });
        }
        mMediaPlayer.start();
    }

    /**
     * Stops the playback of the MP3 file.
     */
    private void stopMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    /**
     * Checks the permission that this app needs and if it has not been granted, it will
     * prompt the user to grant it, otherwise it shuts down the app.
     */
    private void checkPermissions() {
        boolean recordAudioPermissionGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
        if (recordAudioPermissionGranted) {
            start();
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.RECORD_AUDIO }, PERMISSIONS_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                start();
            } else {
                // Permission has been denied before. At this point we should show a dialog to
                // user and explain why this permission is needed and direct him to go to the
                // Permissions settings for the app in the System settings. For this sample, we
                // simply exit to get to the important part.
                Toast.makeText(this, R.string.exiting_for_permissions, Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    /**
     * Starts the main flow of the application.
     */
    private void start() {
        mSoundRecorder = new SoundRecorder(this, VOICE_FILE_NAME, this);
        int[] thumbResources = new int[] { R.id.mic, R.id.play, R.id.music };
        ImageView[] thumbs = new ImageView[3];
        for (int i = 0; i < 3; i++) {
            thumbs[i] = findViewById(thumbResources[i]);
        }
        View containerView = findViewById(R.id.container);
        ImageView expandedView = findViewById(R.id.expanded);
        int animationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
        mUIAnimation = new UIAnimation(containerView, thumbs, expandedView, animationDuration, this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (speakerIsSupported()) {
            checkPermissions();
        } else {
            mOuterCircle.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, R.string.no_speaker_supported, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    protected void onStop() {
        if (mSoundRecorder != null) {
            mSoundRecorder.cleanup();
            mSoundRecorder = null;
        }
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        super.onStop();
    }

    @Override
    public void onPlaybackStopped() {
        mUIAnimation.transitionToHome();
        mUiState = UIAnimation.UIState.HOME;
        mState = AppState.READY;
    }

    /**
     * Determines if the wear device has a built-in speaker and if it is supported. Speaker, even if
     * physically present, is only supported in Android M+ on a wear device..
     */
    public final boolean speakerIsSupported() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PackageManager packageManager = getPackageManager();
            // The results from AudioManager.getDevices can't be trusted unless the device
            // advertises FEATURE_AUDIO_OUTPUT.
            if (!packageManager.hreplacedystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT)) {
                return false;
            }
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
            for (AudioDeviceInfo device : devices) {
                if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public AmbientModeSupport.AmbientCallback getAmbientCallback() {
        return new MyAmbientCallback();
    }

    private clreplaced MyAmbientCallback extends AmbientModeSupport.AmbientCallback {

        /**
         * Prepares the UI for ambient mode.
         */
        @Override
        public void onEnterAmbient(Bundle ambientDetails) {
            super.onEnterAmbient(ambientDetails);
            Log.d(TAG, "onEnterAmbient() " + ambientDetails);
            // Changes views to grey scale.
            Context context = getApplicationContext();
            Resources resources = context.getResources();
            mOuterCircle.setBackgroundColor(ContextCompat.getColor(context, R.color.light_grey));
            mInnerCircle.setBackground(ContextCompat.getDrawable(context, R.drawable.grey_circle));
            mProgressBar.setProgressTintList(resources.getColorStateList(R.color.white, context.getTheme()));
            mProgressBar.setProgressBackgroundTintList(resources.getColorStateList(R.color.black, context.getTheme()));
        }

        /**
         * Restores the UI to active (non-ambient) mode.
         */
        @Override
        public void onExitAmbient() {
            super.onExitAmbient();
            Log.d(TAG, "onExitAmbient()");
            // Changes views to color.
            Context context = getApplicationContext();
            Resources resources = context.getResources();
            mOuterCircle.setBackgroundColor(ContextCompat.getColor(context, R.color.background_color));
            mInnerCircle.setBackground(ContextCompat.getDrawable(context, R.drawable.color_circle));
            mProgressBar.setProgressTintList(resources.getColorStateList(R.color.progressbar_tint, context.getTheme()));
            mProgressBar.setProgressBackgroundTintList(resources.getColorStateList(R.color.progressbar_background_tint, context.getTheme()));
        }
    }
}

19 Source : NotificationService.java
with GNU General Public License v3.0
from AdrianMiozga

public clreplaced NotificationService extends Service {

    private boolean isBreakState;

    private int timeLeft;

    private CountDownTimer countDownTimer;

    private PowerManager.WakeLock wakeLock = null;

    private final Handler handler = new Handler();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = null;
        if (intent != null) {
            action = intent.getStringExtra(Constants.NOTIFICATION_SERVICE);
        }
        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        final SharedPreferences.Editor preferenceEditor = preferences.edit();
        final TimerNotification timerNotification = new TimerNotification();
        boolean isTimerRunning = preferences.getBoolean(Constants.IS_TIMER_RUNNING, false);
        boolean areLongBreaksEnabled = false;
        int sessionsBeforeLongBreak = Constants.DEFAULT_SESSIONS_BEFORE_LONG_BREAK;
        if (intent != null) {
            areLongBreaksEnabled = intent.getBooleanExtra(Constants.ARE_LONG_BREAKS_ENABLED_INTENT, false);
            sessionsBeforeLongBreak = intent.getIntExtra(Constants.SESSIONS_BEFORE_LONG_BREAK_INTENT, Constants.DEFAULT_SESSIONS_BEFORE_LONG_BREAK);
        }
        int workSessionCounter = preferences.getInt(Constants.WORK_SESSION_COUNTER, 0);
        final NotificationCompat.Builder builder = timerNotification.buildNotification(getApplicationContext(), isTimerRunning);
        isBreakState = preferences.getBoolean(Constants.IS_BREAK_STATE, false);
        timeLeft = preferences.getInt(Constants.TIME_LEFT, 0);
        LocalDateTime lastWorkSession = LocalDateTime.parse(preferences.getString(Constants.TIMESTAMP_OF_LAST_WORK_SESSION, LocalDateTime.now().toString()));
        if (timeLeft == 0 && intent != null) {
            // If last work session was over specified time, reset the work counter so that for long break to occur, you
            // have to again complete all sessions.
            if (LocalDateTime.now().isAfter(lastWorkSession.plusHours(Constants.HOURS_BEFORE_WORK_SESSION_COUNT_RESETS))) {
                workSessionCounter = 0;
                preferenceEditor.putInt(Constants.WORK_SESSION_COUNTER, 0);
            }
            if (isBreakState) {
                if (workSessionCounter >= sessionsBeforeLongBreak && areLongBreaksEnabled) {
                    timeLeft = intent.getIntExtra(Constants.LONG_BREAK_DURATION_INTENT, 0) * 60_000;
                    preferenceEditor.putInt(Constants.WORK_SESSION_COUNTER, 0);
                } else {
                    timeLeft = intent.getIntExtra(Constants.BREAK_DURATION_INTENT, 0) * 60_000;
                }
            } else {
                timeLeft = intent.getIntExtra(Constants.WORK_DURATION_INTENT, 0) * 60_000;
            }
        }
        if (preferences.getInt(Constants.LAST_SESSION_DURATION, 0) == 0) {
            preferenceEditor.putInt(Constants.LAST_SESSION_DURATION, timeLeft);
        }
        if (action != null && action.equals(Constants.NOTIFICATION_SERVICE_PAUSE)) {
            cancelCountDownTimer();
            cancelAlarm();
            handler.removeCallbacksAndMessages(null);
            if (wakeLock != null) {
                wakeLock.release();
            }
            if (isBreakState) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    builder.setContentText(getApplicationContext().getString(R.string.break_time_left, Utility.formatTimeForNotification(timeLeft)));
                } else {
                    builder.setContentreplacedle(getApplicationContext().getString(R.string.break_time_left, Utility.formatTimeForNotification(timeLeft)));
                }
            } else {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    builder.setContentText(getApplicationContext().getString(R.string.work_time_left, Utility.formatTimeForNotification(timeLeft)));
                } else {
                    builder.setContentreplacedle(getApplicationContext().getString(R.string.work_time_left, Utility.formatTimeForNotification(timeLeft)));
                }
            }
            startForeground(Constants.TIME_LEFT_NOTIFICATION, builder.build());
        } else {
            // AlarmManager doesn't work when the time is less than 5 seconds,
            // so I have to use another method to trigger the end notification.
            if (timeLeft < 6000) {
                PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
                if (powerManager != null) {
                    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.WAKE_LOCK_TAG);
                }
                if (wakeLock != null) {
                    wakeLock.acquire(timeLeft + 1000);
                }
                handler.postDelayed(() -> startService(new Intent(getApplicationContext(), EndNotificationService.clreplaced)), timeLeft);
            } else {
                AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
                if (alarmManager == null) {
                    return START_STICKY;
                }
                Intent displayEndNotification = new Intent(getApplicationContext(), EndNotificationService.clreplaced);
                PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), Constants.PENDING_INTENT_END_REQUEST_CODE, displayEndNotification, 0);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + timeLeft, pendingIntent);
                } else {
                    alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + timeLeft, pendingIntent);
                }
            }
            countDownTimer = new CountDownTimer(timeLeft, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    timeLeft = (int) millisUntilFinished;
                    preferenceEditor.putInt(Constants.TIME_LEFT, timeLeft);
                    preferenceEditor.apply();
                    if (isBreakState) {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                            builder.setContentText(getApplicationContext().getString(R.string.break_time_left, Utility.formatTimeForNotification(millisUntilFinished)));
                        } else {
                            builder.setContentreplacedle(getApplicationContext().getString(R.string.break_time_left, Utility.formatTimeForNotification(millisUntilFinished)));
                        }
                    } else {
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                            builder.setContentText(getApplicationContext().getString(R.string.work_time_left, Utility.formatTimeForNotification(millisUntilFinished)));
                        } else {
                            builder.setContentreplacedle(getApplicationContext().getString(R.string.work_time_left, Utility.formatTimeForNotification(millisUntilFinished)));
                        }
                    }
                    Intent updateTimer = new Intent(Constants.ON_TICK);
                    updateTimer.putExtra(Constants.TIME_LEFT_INTENT, timeLeft);
                    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(updateTimer);
                    startForeground(Constants.TIME_LEFT_NOTIFICATION, builder.build());
                }

                @Override
                public void onFinish() {
                    stopSelf();
                }
            }.start();
        }
        return START_STICKY;
    }

    private void cancelCountDownTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelCountDownTimer();
        cancelAlarm();
        handler.removeCallbacksAndMessages(null);
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
        }
        SharedPreferences.Editor preferenceEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        preferenceEditor.putInt(Constants.TIME_LEFT, 0);
        preferenceEditor.apply();
    }

    private void cancelAlarm() {
        AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        if (alarmManager == null) {
            return;
        }
        Intent displayEndNotification = new Intent(getApplicationContext(), EndNotificationService.clreplaced);
        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), Constants.PENDING_INTENT_END_REQUEST_CODE, displayEndNotification, 0);
        alarmManager.cancel(pendingIntent);
    }
}

19 Source : EndNotificationService.java
with GNU General Public License v3.0
from AdrianMiozga

public clreplaced EndNotificationService extends Service {

    private CountDownTimer reminderCountDownTimer;

    private PowerManager.WakeLock wakeLock = null;

    private final long[] vibrationPattern = new long[] { 0, 500, 250, 500 };

    private final long vibrationPatternLength = sumArrayElements(vibrationPattern);

    private long sumArrayElements(long[] vibrationPattern) {
        int sum = 0;
        for (Long element : vibrationPattern) {
            sum += element;
        }
        return sum;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor preferenceEditor = preferences.edit();
        boolean isBreakState = preferences.getBoolean(Constants.IS_BREAK_STATE, false);
        int activityId = preferences.getInt(Constants.CURRENT_ACTIVITY_ID, 1);
        Database database = Database.getInstance(this);
        Database.databaseExecutor.execute(() -> {
            if (!database.activityDao().isDNDKeptOnBreaks(activityId)) {
                Utility.setDoNotDisturb(getApplicationContext(), AudioManager.RINGER_MODE_NORMAL, activityId);
            }
        });
        preferenceEditor.putBoolean(Constants.IS_TIMER_RUNNING, false);
        preferenceEditor.putInt(Constants.TIME_LEFT, 0);
        preferenceEditor.putBoolean(Constants.IS_STOP_BUTTON_VISIBLE, true);
        preferenceEditor.putBoolean(Constants.IS_START_BUTTON_VISIBLE, true);
        preferenceEditor.putBoolean(Constants.IS_PAUSE_BUTTON_VISIBLE, false);
        preferenceEditor.putBoolean(Constants.IS_TIMER_BLINKING, true);
        if (isBreakState) {
            preferenceEditor.putBoolean(Constants.IS_SKIP_BUTTON_VISIBLE, false);
            preferenceEditor.putBoolean(Constants.IS_WORK_ICON_VISIBLE, true);
            preferenceEditor.putBoolean(Constants.IS_BREAK_ICON_VISIBLE, false);
            preferenceEditor.putBoolean(Constants.IS_BREAK_STATE, false);
            preferenceEditor.putBoolean(Constants.CENTER_BUTTONS, true);
        } else {
            preferenceEditor.putBoolean(Constants.IS_SKIP_BUTTON_VISIBLE, true);
            preferenceEditor.putBoolean(Constants.IS_WORK_ICON_VISIBLE, false);
            preferenceEditor.putBoolean(Constants.IS_BREAK_ICON_VISIBLE, true);
            preferenceEditor.putBoolean(Constants.IS_BREAK_STATE, true);
            preferenceEditor.putBoolean(Constants.CENTER_BUTTONS, false);
            preferenceEditor.putString(Constants.TIMESTAMP_OF_LAST_WORK_SESSION, LocalDateTime.now().toString());
        }
        preferenceEditor.putInt(Constants.LAST_SESSION_DURATION, 0);
        if (isBreakState) {
            Utility.updateDatabaseBreaks(getApplicationContext(), preferences.getInt(Constants.LAST_SESSION_DURATION, 0), activityId);
        } else {
            Utility.updateDatabaseCompletedWorks(getApplicationContext(), preferences.getInt(Constants.LAST_SESSION_DURATION, 0), activityId);
            preferenceEditor.putInt(Constants.WORK_SESSION_COUNTER, preferences.getInt(Constants.WORK_SESSION_COUNTER, 0) + 1);
        }
        preferenceEditor.apply();
        Intent displayMainActivity = new Intent(getApplicationContext(), MainActivity.clreplaced);
        displayMainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(displayMainActivity);
        showEndNotification();
        vibrate();
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void showEndNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), Constants.CHANNEL_TIMER_COMPLETED).setSmallIcon(R.drawable.notification_icon).setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary)).setPriority(NotificationCompat.PRIORITY_DEFAULT).setCategory(NotificationCompat.CATEGORY_ALARM).setOngoing(true).setDefaults(Notification.DEFAULT_SOUND).setLights(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), 500, 2000);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            builder.setContentreplacedle(getString(R.string.app_name));
        }
        Intent intent = new Intent(this, MainActivity.clreplaced);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, Constants.PENDING_INTENT_OPEN_APP_REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(pendingIntent);
        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isBreakState = preferences.getBoolean(Constants.IS_BREAK_STATE, false);
        if (isBreakState) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                builder.setContentText(getString(R.string.break_time));
            } else {
                builder.setContentreplacedle(getString(R.string.break_time));
            }
        } else {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                builder.setContentText(getString(R.string.work_time));
            } else {
                builder.setContentreplacedle(getString(R.string.work_time));
            }
        }
        startForeground(Constants.ON_FINISH_NOTIFICATION, builder.build());
    }

    private void vibrate() {
        final Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator == null) {
            return;
        }
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (powerManager != null) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.WAKE_LOCK_TAG);
        }
        if (wakeLock != null) {
            wakeLock.acquire(Constants.VIBRATION_REMINDER_FREQUENCY + vibrationPatternLength);
        }
        reminderCountDownTimer = new CountDownTimer(Constants.VIBRATION_REMINDER_FREQUENCY, 1000) {

            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    vibrator.vibrate(VibrationEffect.createWaveform(vibrationPattern, VibrationEffect.DEFAULT_AMPLITUDE));
                } else {
                    vibrator.vibrate(500);
                }
                if (wakeLock != null) {
                    wakeLock.acquire(Constants.VIBRATION_REMINDER_FREQUENCY + vibrationPatternLength);
                }
                start();
            }
        }.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (reminderCountDownTimer != null) {
            reminderCountDownTimer.cancel();
        }
        if (wakeLock != null) {
            wakeLock.release();
        }
    }
}

19 Source : AppTimeDialogService.java
with MIT License
from addiegupta

/**
 * Foreground service that handles background tasks of counting time,launching stop dialog etc
 */
public clreplaced AppTimeDialogService extends Service {

    private static final String TIME_KEY = "time";

    private static final String TARGET_PACKAGE_KEY = "target_package";

    private static final String APP_COLOR_KEY = "app_color";

    private static final String TEXT_COLOR_KEY = "text_color";

    private static final int APP_STOPPED_NOTIF_ID = 77;

    private static final String CALLING_CLreplaced_KEY = "calling_clreplaced";

    private static final String ACTION_STOP_SERVICE = "action_stop_service";

    private SharedPreferences preferences;

    private static final int FOREGROUND_NOTIF_ID = 104;

    private static final String DISPLAY_1_MIN = "display_1_min";

    private int appTime;

    private boolean hasUsageAccess;

    private String targetPackage;

    private String mAppName;

    private Bitmap mAppIcon;

    private int mAppColor;

    private int mTextColor;

    CountDownTimer cdt = null;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        if (cdt != null) {
            cdt.cancel();
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            stopSelf();
        } else {
            if (intent.getAction() != null && ACTION_STOP_SERVICE.equals(intent.getAction())) {
                if (cdt != null) {
                    cdt.cancel();
                }
                stopForeground(true);
                stopSelf();
            } else {
                initialiseVariables(intent);
                checkIfPermissionGrantedManually();
                fetchAppData();
                runForegroundService();
                setupAndStartCDT();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void checkIfPermissionGrantedManually() {
        // Check if permission has been granted manually
        if (!preferences.getBoolean(getString(R.string.usage_permission_pref), false)) {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && hasUsageStatsPermission(this)) {
                preferences.edit().putBoolean(getString(R.string.usage_permission_pref), true).apply();
            }
        }
        hasUsageAccess = preferences.getBoolean(getString(R.string.usage_permission_pref), false);
    }

    /**
     * Initialises variables to be used
     *
     * @param intent starting intent
     */
    private void initialiseVariables(Intent intent) {
        if (cdt != null) {
            cdt.cancel();
        }
        appTime = intent.getIntExtra(TIME_KEY, 0);
        targetPackage = intent.getStringExtra(TARGET_PACKAGE_KEY);
        mAppColor = intent.getIntExtra(APP_COLOR_KEY, getResources().getColor(R.color.black));
        mTextColor = intent.getIntExtra(TEXT_COLOR_KEY, getResources().getColor(R.color.white));
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
    }

    /**
     * Starts countdown timer for required time as specified by the clreplaced starting this service
     */
    private void setupAndStartCDT() {
        cdt = new CountDownTimer(appTime, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                Timber.i("Countdown seconds remaining in ATDService: %s", millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                Timber.i("Timer finished.Starting activity");
                showStopDialog();
                stopForeground(true);
                stopSelf();
            }
        };
        cdt.start();
    }

    /**
     * Displays stop dialog on top of the current activity ( has a transparent background due to DialogActivity)
     */
    private void showStopDialog() {
        Intent dialogIntent = new Intent(AppTimeDialogService.this, DialogActivity.clreplaced);
        dialogIntent.putExtra(TARGET_PACKAGE_KEY, targetPackage);
        dialogIntent.putExtra(APP_COLOR_KEY, mAppColor);
        dialogIntent.putExtra(TEXT_COLOR_KEY, mTextColor);
        dialogIntent.putExtra(CALLING_CLreplaced_KEY, getClreplaced().getSimpleName());
        dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        // Duration equal to 1 minute
        if (appTime == 60000)
            dialogIntent.putExtra(DISPLAY_1_MIN, false);
        if (hasUsageAccess) {
            // Checks which app is in foreground
            AppChecker appChecker = new AppChecker();
            String packageName = appChecker.getForegroundApp(AppTimeDialogService.this);
            // Creates intent to display
            if (packageName.equals(targetPackage)) {
                Timber.d("App is in use");
                startActivity(dialogIntent);
            } else {
                issueAppStoppedNotification();
            }
        } else // No usage permission, show dialog without checking foreground app
        {
            startActivity(dialogIntent);
        }
    }

    /**
     * Checks if usage permission has been granted
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    boolean hasUsageStatsPermission(Context context) {
        AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), context.getPackageName());
        boolean granted = mode == AppOpsManager.MODE_ALLOWED;
        preferences.edit().putBoolean(getString(R.string.usage_permission_pref), granted).apply();
        return granted;
    }

    /**
     * Fetches data of target app i.e. application name and icon
     */
    private void fetchAppData() {
        ApplicationInfo appInfo;
        PackageManager pm = getPackageManager();
        try {
            Drawable iconDrawable = pm.getApplicationIcon(targetPackage);
            mAppIcon = Utils.getBitmapFromDrawable(iconDrawable);
            appInfo = pm.getApplicationInfo(targetPackage, 0);
        } catch (final PackageManager.NameNotFoundException e) {
            appInfo = null;
            mAppIcon = null;
        }
        mAppName = (String) (appInfo != null ? pm.getApplicationLabel(appInfo) : "(unknown)");
    }

    /**
     * App is no longer running. Display notification instead of dialog
     */
    private void issueAppStoppedNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
        String channelId = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // The id of the channel.
            String CHANNEL_ID = "timesapp_app_stopped";
            // The user-visible name of the channel.
            String channelName = getString(R.string.notif_app_stopped_channel_name);
            int importance = NotificationManager.IMPORTANCE_LOW;
            channelId = createNotificationChannel(CHANNEL_ID, channelName, importance);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(AppTimeDialogService.this, channelId);
        String replacedle = mAppName + " " + getString(R.string.app_closed_notification_replacedle);
        builder.setContentreplacedle(replacedle).setSmallIcon(R.drawable.app_notification_icon).setContentIntent(PendingIntent.getActivity(AppTimeDialogService.this, 0, new Intent(), 0)).setLargeIcon(mAppIcon).setColor(getResources().getColor(R.color.colorPrimary)).setSubText(getString(R.string.app_closed_notification_subreplacedle)).setAutoCancel(true);
        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        if (notificationManager != null) {
            notificationManager.notify(APP_STOPPED_NOTIF_ID, notification);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void runForegroundService() {
        String channelId = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = createNotificationChannel("timesapp_fg_service", "Background Service Notification", NotificationManager.IMPORTANCE_LOW);
        }
        Intent notificationIntent = new Intent(this, ForegroundServiceActivity.clreplaced);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
        Intent appLaunchIntent = getPackageManager().getLaunchIntentForPackage(targetPackage);
        PendingIntent actionPendingIntent = PendingIntent.getActivity(this, 1, appLaunchIntent, 0);
        NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder(R.drawable.ic_exit_to_app_black_24dp, "Return to " + mAppName, actionPendingIntent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setCategory(Notification.CATEGORY_SERVICE);
        }
        if (preferences.getBoolean(getString(R.string.pref_notification_done_key), true)) {
            Intent stopSelfIntent = new Intent(this, AppTimeDialogService.clreplaced);
            stopSelfIntent.setAction(ACTION_STOP_SERVICE);
            PendingIntent stopSelfPIntent = PendingIntent.getService(this, 0, stopSelfIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder stopActionBuilder = new NotificationCompat.Action.Builder(R.drawable.ic_clear_black_24dp, "Done", stopSelfPIntent);
            builder.addAction(stopActionBuilder.build());
        }
        Notification notification = builder.setOngoing(true).setContentText(getString(R.string.app_running_service_notif_text)).setSubText(getString(R.string.tap_for_more_info_foreground_notif)).setColor(getResources().getColor(R.color.colorPrimary)).addAction(actionBuilder.build()).setPriority(Notification.PRIORITY_MIN).setSmallIcon(R.drawable.app_notification_icon).setContentIntent(pendingIntent).build();
        startForeground(FOREGROUND_NOTIF_ID, notification);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel chan = new NotificationChannel(channelId, channelName, importance);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.createNotificationChannel(chan);
        }
        return channelId;
    }
}

19 Source : DownTimer.java
with Apache License 2.0
from 13120241790

/**
 * [倒计时类]
 *
 * @author devin.hu
 * @version 1.0
 * @date 2014-12-1
 */
public clreplaced DownTimer {

    private final String TAG = DownTimer.clreplaced.getSimpleName();

    private CountDownTimer mCountDownTimer;

    private DownTimerListener listener;

    /**
     * [开始倒计时功能]<BR>
     * [倒计为time长的时间,时间间隔为每秒]
     * @param time
     */
    public void startDown(long time) {
        startDown(time, 1000);
    }

    /**
     * [倒计为time长的时间,时间间隔为mills]
     * @param time
     * @param mills
     */
    public void startDown(long time, long mills) {
        mCountDownTimer = new CountDownTimer(time, mills) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (listener != null) {
                    listener.onTick(millisUntilFinished);
                } else {
                    NLog.e(TAG, "DownTimerListener 监听不能为空");
                }
            }

            @Override
            public void onFinish() {
                if (listener != null) {
                    listener.onFinish();
                } else {
                    NLog.e(TAG, "DownTimerListener 监听不能为空");
                }
                if (mCountDownTimer != null)
                    mCountDownTimer.cancel();
            }
        }.start();
    }

    /**
     * [停止倒计时功能]<BR>
     */
    public void stopDown() {
        if (mCountDownTimer != null)
            mCountDownTimer.cancel();
    }

    /**
     * [设置倒计时监听]<BR>
     * @param listener
     */
    public void setListener(DownTimerListener listener) {
        this.listener = listener;
    }
}

19 Source : SuperLikeLayout.java
with Apache License 2.0
from 1067899750

/**
 * @author puyantao
 * @description
 * @date 2020/7/29 16:21
 */
public clreplaced SuperLikeLayout extends View implements AnimationEndListener {

    private long totalTime = 60 * 1000;

    private static final String TAG = "SuperLikeLayout";

    /**
     * 移动时间间隔
     */
    private static final long INTERVAL = 40;

    /**
     * 默认默认缓存数组的个数
     */
    private static final int MAX_FRAME_SIZE = 16;

    /**
     * 默认图片个数
     */
    private static final int ERUPTION_ELEMENT_AMOUNT = 4;

    private AnimationFramePool animationFramePool;

    private AnimationHandler mAnimationHandler;

    private BitmapProvider.Provider provider;

    /**
     * 是否显示喷射图标
     */
    private boolean hasEruptionAnimation;

    /**
     * 是否显示文字
     */
    private boolean hasTextAnimation;

    private View mView;

    private boolean isLongClick;

    private CountDownTimer countDownTimer = new CountDownTimer(totalTime, 200) {

        @Override
        public void onTick(long millisUntilFinished) {
            // 执行任务
            launch(mView);
        }

        @Override
        public void onFinish() {
            if (countDownTimer != null) {
                countDownTimer.start();
            }
        }
    };

    public SuperLikeLayout(@NonNull Context context) {
        this(context, null);
    }

    public SuperLikeLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SuperLikeLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        mAnimationHandler = new AnimationHandler(this);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SuperLikeLayout, defStyleAttr, 0);
        // 设置图片个数
        int elementAmount = a.getInteger(R.styleable.SuperLikeLayout_eruption_element_amount, ERUPTION_ELEMENT_AMOUNT);
        // 默认缓存数组的个数
        int maxFrameSize = a.getInteger(R.styleable.SuperLikeLayout_max_eruption_total, MAX_FRAME_SIZE);
        // 是否显示喷射图标
        hasEruptionAnimation = a.getBoolean(R.styleable.SuperLikeLayout_show_emoji, true);
        // 是否显示文字
        hasTextAnimation = a.getBoolean(R.styleable.SuperLikeLayout_show_text, true);
        a.recycle();
        animationFramePool = new AnimationFramePool(maxFrameSize, elementAmount);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        if (!animationFramePool.hasRunningAnimation()) {
            return;
        }
        // 遍历所有AnimationFrame 并绘制Element
        // note: 需要倒序遍历 nextFrame方法可能会改变runningFrameList Size 导致异常
        List<AnimationFrame> runningFrameList = animationFramePool.getRunningFrameList();
        for (int i = runningFrameList.size() - 1; i >= 0; i--) {
            AnimationFrame animationFrame = runningFrameList.get(i);
            List<Element> elementList = animationFrame.nextFrame(INTERVAL);
            for (Element element : elementList) {
                // 绘制图片
                Paint paint = new Paint();
                // 设置透明程度
                paint.setAlpha(element.getAlpha());
                canvas.drawBitmap(element.getBitmap(), element.getX(), element.getY(), paint);
            }
        }
    }

    /**
     * 启动动画
     *
     * @param v 单次点击试图
     */
    private void launch(View v) {
        int width = v.getWidth();
        int height = v.getHeight();
        int x = (int) (v.getX() + width / 2);
        int y = (int) (v.getY() + height / 2);
        if (!hasEruptionAnimation && !hasTextAnimation) {
            return;
        }
        // 喷射动画
        if (hasEruptionAnimation) {
            AnimationFrame eruptionAnimationFrame = animationFramePool.obtain(EruptionAnimationFrame.TYPE);
            if (eruptionAnimationFrame != null && !eruptionAnimationFrame.isRunning()) {
                eruptionAnimationFrame.setAnimationEndListener(this);
                eruptionAnimationFrame.prepare(width, height, x, y, getProvider());
            }
        }
        // combo动画
        if (hasTextAnimation) {
            AnimationFrame textAnimationFrame = animationFramePool.obtain(TextAnimationFrame.TYPE);
            if (textAnimationFrame != null) {
                textAnimationFrame.setLongClick(isLongClick);
                textAnimationFrame.setAnimationEndListener(this);
                textAnimationFrame.prepare(width, height, x, y, getProvider());
            }
        }
        mAnimationHandler.removeMessages(AnimationHandler.MESSAGE_CODE_REFRESH_ANIMATION);
        mAnimationHandler.sendEmptyMessageDelayed(AnimationHandler.MESSAGE_CODE_REFRESH_ANIMATION, INTERVAL);
    }

    /**
     * 长按试图
     *
     * @param view
     */
    public void longClickView(View view) {
        this.mView = view;
        stop();
        isLongClick = true;
        // 主线程中调用:
        countDownTimer.start();
    }

    /**
     * 单点试图
     *
     * @param view
     */
    public void clickView(View view) {
        this.mView = view;
        isLongClick = false;
        launch(view);
    }

    /**
     * 结束计时
     */
    public void stop() {
        countDownTimer.cancel();
    }

    public boolean hasAnimation() {
        return animationFramePool.hasRunningAnimation();
    }

    /**
     * 设置数据对象
     *
     * @param provider
     */
    public void setProvider(BitmapProvider.Provider provider) {
        this.provider = provider;
    }

    public BitmapProvider.Provider getProvider() {
        if (provider == null) {
            provider = new BitmapProvider.Builder(getContext()).build();
        }
        return provider;
    }

    /**
     * 回收SurpriseView  添加至空闲队列方便下次使用
     */
    private void onRecycle(AnimationFrame animationFrame) {
        Log.v(TAG, "=== AnimationFrame recycle ===");
        animationFrame.reset();
        animationFramePool.recycle(animationFrame);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (!hasAnimation()) {
            return;
        }
        // 回收所有动画 并暂停动画
        animationFramePool.recycleAll();
        mAnimationHandler.removeMessages(AnimationHandler.MESSAGE_CODE_REFRESH_ANIMATION);
    }

    /**
     * 动画结束
     *
     * @param animationFrame
     */
    @Override
    public void onAnimationEnd(AnimationFrame animationFrame) {
        onRecycle(animationFrame);
    }

    private static final clreplaced AnimationHandler extends Handler {

        public static final int MESSAGE_CODE_REFRESH_ANIMATION = 1001;

        private WeakReference<SuperLikeLayout> weakReference;

        public AnimationHandler(SuperLikeLayout superLikeLayout) {
            weakReference = new WeakReference<>(superLikeLayout);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MESSAGE_CODE_REFRESH_ANIMATION && weakReference != null && weakReference.get() != null) {
                weakReference.get().invalidate();
                // 动画还未结束继续刷新
                if (weakReference.get().hasAnimation()) {
                    sendEmptyMessageDelayed(MESSAGE_CODE_REFRESH_ANIMATION, INTERVAL);
                }
            }
        }
    }

    public void onDestroy() {
        mAnimationHandler.removeCallbacksAndMessages(null);
    }
}

18 Source : MainActivity.java
with GNU General Public License v3.0
from zzzmobile

public clreplaced MainActivity extends AppCompatActivity implements iConstants, NavigationView.OnNavigationItemSelectedListener {

    private String postUrl = "http://www.google.com";

    private WebView webView;

    private ProgressBar progressBar;

    private float m_downX;

    private EditText SearchText;

    final Activity activity = this;

    FloatingActionButton fab;

    private boolean AdblockEnabled = true;

    private BottomNavigationView bottomNavigationView;

    private CountDownTimer timer;

    private Boolean SearchHasFocus = false;

    private View bottomSheet;

    private View webViewCon;

    SharedPreferences sharedPrefs;

    String URL;

    GridView HomeView;

    // private AdView adView;
    // private IntersreplacedialAd intersreplacedialAd;
    private IntersreplacedialAd mIntersreplacedialAd;

    PublisherIntersreplacedialAd mPublisherIntersreplacedialAd;

    public static boolean mAdIsLoading = false;

    public static final int REQUEST_PERMISSION_CODE = 1001;

    public static final String REQUEST_PERMISSION = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AppLovinSdk.initializeSdk(MainActivity.this);
        // MobileAds.initialize(this, ADMOB_APP_ID);
        // mIntersreplacedialAd = new IntersreplacedialAd(this);
        // mIntersreplacedialAd.setAdUnitId(ADMOB_INTERSreplacedIAL_ID);
        // mIntersreplacedialAd.loadAd(new AdRequest.Builder().build());
        // 
        // mIntersreplacedialAd.setAdListener(new AdListener() {
        // 
        // @Override
        // public void onAdLoaded(){
        // if (!mAdIsLoading) {
        // mIntersreplacedialAd.show();
        // if(AppLovinIntersreplacedialAd.isAdReadyToDisplay(MainActivity.this)){
        // // An ad is available to display.  It's safe to call show.
        // AppLovinIntersreplacedialAd.show(MainActivity.this);
        // Log.d("APPLOVIN ADS Ready=====>","YES");
        // }
        // else{
        // // No ad is available to display.  Perform failover logic...
        // Log.d("Not Ready=====>","YES");
        // 
        // }
        // mAdIsLoading = true;
        // }
        // 
        // }
        // 
        // });
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        webView = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        SearchText = (EditText) findViewById(R.id.SearchText);
        SearchText.setSelectAllOnFocus(true);
        bottomSheet = findViewById(R.id.design_bottom_sheet);
        HomeView = (GridView) findViewById(R.id.HomePage);
        webViewCon = (View) findViewById(R.id.webViewCon);
        // bottomNavigationView;
        bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        OnPrepareBottomNav(bottomNavigationView.getMenu());
        HomeView.setAdapter(new SitesAdapter(this));
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        // RelativeLayout adViewContainer = (RelativeLayout) findViewById(R.id.adViewContainer);
        // intersreplacedialAd = new IntersreplacedialAd(this, FACEBOOK_INTERSreplacedIAL_ID);
        // 
        // adView = new AdView(this, FACEBOOK_BANNER_ID, AdSize.BANNER_320_50);
        // 
        // adViewContainer.addView(adView);
        // AdSettings.addTestDevice("d07d57d86bba7e633a9f017d267f2949");
        // adView.loadAd();
        /**
         * On Click event for Single Gridview Item
         */
        HomeView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                webView.loadUrl(HomePageURI[position]);
                SwithcView(true);
            }
        });
        AdblockEnabled = sharedPrefs.getBoolean("ADBLOCK", true);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch(item.gereplacedemId()) {
                    case R.id.action_home:
                        SwithcView(false);
                        break;
                    case R.id.action_bookmark:
                        iUtils.bookmarkUrl(MainActivity.this, webView.getUrl());
                        if (iUtils.isBookmarked(MainActivity.this, webView.getUrl())) {
                            item.setIcon(R.drawable.ic_bookmark_grey_800_24dp);
                            item.getIcon().setAlpha(255);
                            iUtils.ShowToast(MainActivity.this, "Bookmarked");
                        } else {
                            item.setIcon(R.drawable.ic_bookmark_border_grey_800_24dp);
                            item.getIcon().setAlpha(130);
                        }
                        break;
                    case R.id.action_back:
                        back();
                        break;
                    case R.id.action_forward:
                        forward();
                        break;
                }
                return true;
            }
        });
        // WebView
        initWebView();
        // webView.loadUrl(postUrl);
        SearchText.setText(webView.getUrl());
        SearchText.setSelected(false);
        isNeedGrantPermission();
        // Floating Button :)
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setVisibility(View.GONE);
        fab.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                GeneratingDownloadLinks.Start(MainActivity.this, webView.getUrl(), webView.getreplacedle());
            // loadIntersreplacedialAd();
            // // For intersreplacedials
            // if(AppLovinIntersreplacedialAd.isAdReadyToDisplay(MainActivity.this)){
            // // An ad is available to display.  It's safe to call show.
            // AppLovinIntersreplacedialAd.show(MainActivity.this);
            // Log.d("APPLOVIN ADS Ready=====>","YES");
            // }
            // else{
            // // No ad is available to display.  Perform failover logic...
            // Log.d("Not Ready=====>","YES");
            // 
            // }
            }
        });
        if (intent.hasExtra("URL")) {
            URL = extras.getString("URL");
            if (!URL.equals("")) {
                LoadFromIntent(URL);
            }
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        // Search Text
        SearchText.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if ((i == EditorInfo.IME_ACTION_DONE) || ((keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (keyEvent.getAction() == KeyEvent.ACTION_DOWN))) {
                    String url = SearchText.getText().toString();
                    // iUtils.ShowToast(MainActivity.this,url);
                    SearchText.clearFocus();
                    SwithcView(true);
                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    in.hideSoftInputFromWindow(SearchText.getWindowToken(), 0);
                    if (iUtils.checkURL(url)) {
                        if (!url.contains("http://") || !url.contains("https://")) {
                            if (url.contains("http//") || url.contains("https//")) {
                                url = url.replace("http//", "http://");
                                url = url.replace("https//", "https://");
                            } else {
                                url = "http://" + url;
                            }
                        }
                        webView.loadUrl(url);
                        SearchText.setText(webView.getUrl());
                    } else {
                        String Searchurl = String.format(SEARCH_ENGINE, url);
                        webView.loadUrl(Searchurl);
                        SearchText.setText(webView.getUrl());
                    }
                    return true;
                }
                return false;
            }
        });
        timer = new CountDownTimer(2000, 20) {

            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                try {
                    UpdateUi();
                // iUtils.ShowToast(MainActivity.this,"working");
                } catch (Exception e) {
                    Log.e("TimerError", "Error: " + e.toString());
                }
            }
        }.start();
        SearchText.setOnFocusChangeListener(focusListener);
    }

    private View.OnFocusChangeListener focusListener = new View.OnFocusChangeListener() {

        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                SearchHasFocus = true;
            } else {
                SearchHasFocus = false;
            }
        }
    };

    public void UpdateUi() {
        String WebUrl = webView.getUrl();
        String SearchUrl = SearchText.getText().toString();
        if (!SearchHasFocus) {
            if (!WebUrl.equals(SearchUrl)) {
                SearchText.setText(WebUrl);
            }
            // iUtils.ShowToast(MainActivity.this,WebUrl);
            // DownloadHandle(false, WebUrl);
            // for (int i = 0; i < SITES_URL.length; i++) {
            // if (WebUrl.contains(SITES_URL[i])) {
            // DownloadHandle(true, WebUrl);
            // }
            // }
            OnPrepareBottomNav(bottomNavigationView.getMenu());
        }
        timer.start();
    }

    private void LoadFromIntent(String url) {
        SwithcView(true);
        webView.loadUrl(url);
    }

    private void SwithcView(Boolean show) {
        if (show) {
            webViewCon.setVisibility(View.VISIBLE);
            HomeView.setVisibility(View.GONE);
            fab.setVisibility(View.VISIBLE);
        } else {
            webViewCon.setVisibility(View.GONE);
            HomeView.setVisibility(View.VISIBLE);
            webView.stopLoading();
            webView.loadUrl("about:blank");
            SearchText.setText("");
            fab.setVisibility(View.GONE);
        }
    }

    private void initWebView() {
        webView.setWebChromeClient(new MyWebChromeClient(this));
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
                OnPrepareBottomNav(bottomNavigationView.getMenu());
            }

            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("intent://")) {
                    try {
                        Intent furl = Intent.parseUri(url, 1);
                        if (getPackageManager().getLaunchIntentForPackage(furl.getPackage()) != null) {
                            startActivity(furl);
                            return true;
                        }
                        Intent intent = new Intent("android.intent.action.VIEW");
                        intent.setData(Uri.parse("market://details?id=" + furl.getPackage()));
                        startActivity(intent);
                        return true;
                    } catch (URISyntaxException e) {
                        iUtils.ShowToast(MainActivity.this, "No Application Found!");
                        e.printStackTrace();
                    }
                } else if (url.startsWith("market://")) {
                    try {
                        Intent r1 = Intent.parseUri(url, 1);
                        if (r1 == null) {
                            return true;
                        }
                        startActivity(r1);
                        return true;
                    } catch (Throwable e22) {
                        iUtils.ShowToast(MainActivity.this, "No Application Found!");
                        e22.printStackTrace();
                        return true;
                    }
                } else {
                    SearchText.setText(url);
                    webView.loadUrl(url);
                }
                return true;
            }

            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if (url.startsWith("intent://")) {
                    try {
                        Intent furl = Intent.parseUri(url, 1);
                        if (getPackageManager().getLaunchIntentForPackage(furl.getPackage()) != null) {
                            startActivity(furl);
                            return true;
                        }
                        Intent intent = new Intent("android.intent.action.VIEW");
                        intent.setData(Uri.parse("market://details?id=" + furl.getPackage()));
                        startActivity(intent);
                        return true;
                    } catch (URISyntaxException e) {
                        iUtils.ShowToast(MainActivity.this, "No Application Found!");
                        e.printStackTrace();
                    }
                } else if (url.startsWith("market://")) {
                    try {
                        Intent r1 = Intent.parseUri(url, 1);
                        if (r1 == null) {
                            return true;
                        }
                        startActivity(r1);
                        return true;
                    } catch (Throwable e22) {
                        iUtils.ShowToast(MainActivity.this, "No Application Found!");
                        e22.printStackTrace();
                        return true;
                    }
                } else {
                    SearchText.setText(url);
                    webView.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);
                // view.loadUrl("javascript:window.android.onUrlChange(window.location.href);");
                OnPrepareBottomNav(bottomNavigationView.getMenu());
            }

            @Deprecated
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (AdblockEnabled && new AdBlock(MainActivity.this).isAd(url)) {
                    return new WebResourceResponse("text/plain", "UTF-8", new ByteArrayInputStream("".getBytes()));
                }
                return super.shouldInterceptRequest(view, url);
            }

            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (AdblockEnabled && new AdBlock(MainActivity.this).isAd(request.getUrl().toString())) {
                        return new WebResourceResponse("text/plain", "UTF-8", new ByteArrayInputStream("".getBytes()));
                    }
                }
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                progressBar.setVisibility(View.GONE);
                OnPrepareBottomNav(bottomNavigationView.getMenu());
            }
        });
        webView.clearCache(true);
        webView.clearHistory();
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        webView.setHorizontalScrollBarEnabled(false);
        WebSettings webSettings = webView.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setDomStorageEnabled(true);
        webView.addJavascriptInterface(new MyJavaScriptInterface(), "android");
        webView.setWebChromeClient(new WebChromeClient() {
        });
        webView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                if (event.getPointerCount() > 1) {
                    // Multi touch detected
                    return true;
                }
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        {
                            // save the x
                            m_downX = event.getX();
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        {
                            // set x so that it doesn't move
                            event.setLocation(m_downX, event.getY());
                        }
                        break;
                }
                return false;
            }
        });
    }

    clreplaced MyJavaScriptInterface {

        @JavascriptInterface
        public void onUrlChange(String url) {
        }
    }

    // private void loadIntersreplacedialAd() {
    // intersreplacedialAd.setAdListener(new IntersreplacedialAdListener() {
    // @Override
    // public void onIntersreplacedialDisplayed(Ad ad) {
    // // Intersreplacedial displayed callback
    // }
    // 
    // @Override
    // public void onIntersreplacedialDismissed(Ad ad) {
    // // Intersreplacedial dismissed callback
    // }
    // 
    // @Override
    // public void onError(Ad ad, AdError adError) {
    // // Ad error callback
    // 
    // }
    // 
    // @Override
    // public void onAdLoaded(Ad ad) {
    // // Show the ad when it's done loading.
    // intersreplacedialAd.show();
    // }
    // 
    // @Override
    // public void onAdClicked(Ad ad) {
    // // Ad clicked callback
    // }
    // 
    // @Override
    // public void onLoggingImpression(Ad ad) {
    // 
    // }
    // });
    // 
    // // For auto play video ads, it's recommended to load the ad
    // // at least 30 seconds before it is shown
    // intersreplacedialAd.loadAd();
    // }
    private void GetMedia() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setreplacedle("Enter URL to get media ");
        // Set up the input
        final EditText input = new EditText(this);
        // Specify the type of input expected; this, for example, sets the input as a preplacedword, and will mask the text
        input.setInputType(InputType.TYPE_CLreplaced_TEXT);
        builder.setView(input);
        // Set up the buttons
        builder.setPositiveButton("Get", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // iUtils.ShowToast(MainActivity.this,input.getText().toString());
                String url = input.getText().toString();
                if (iUtils.checkURL(url)) {
                    GeneratingDownloadLinks.Start(MainActivity.this, input.getText().toString(), "");
                // For intersreplacedials
                } else {
                    iUtils.ShowToast(MainActivity.this, URL_NOT_SUPPORTED);
                }
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (webView.canGoBack()) {
                back();
            } else {
                webView.loadUrl("");
                webView.stopLoading();
                super.onBackPressed();
            }
        }
    }

    public void DownloadHandle(boolean show, final String postUrl) {
        if (show) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    fab.setVisibility(View.VISIBLE);
                }
            });
        } else {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    fab.setVisibility(View.GONE);
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public boolean OnPrepareBottomNav(Menu menu) {
        // Log.e("ERROR BOOKMARK",webView.getUrl());
        if (!iUtils.isBookmarked(this, SearchText.getText().toString())) {
            menu.gereplacedem(1).setIcon(R.drawable.ic_bookmark_border_grey_800_24dp);
            menu.gereplacedem(1).getIcon().setAlpha(130);
        } else {
            menu.gereplacedem(1).setIcon(R.drawable.ic_bookmark_grey_800_24dp);
            menu.gereplacedem(1).getIcon().setAlpha(255);
        }
        if (!webView.canGoBack()) {
            menu.gereplacedem(2).setEnabled(false);
            menu.gereplacedem(2).getIcon().setAlpha(130);
        } else {
            menu.gereplacedem(2).setEnabled(true);
            menu.gereplacedem(2).getIcon().setAlpha(255);
        }
        if (!webView.canGoForward()) {
            menu.gereplacedem(3).setEnabled(false);
            menu.gereplacedem(3).getIcon().setAlpha(130);
        } else {
            menu.gereplacedem(3).setEnabled(true);
            menu.gereplacedem(3).getIcon().setAlpha(255);
        }
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        if (item.gereplacedemId() == R.id.action_downloads) {
            startActivity(new Intent("android.intent.action.VIEW_DOWNLOADS"));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void back() {
        if (webView.canGoBack()) {
            WebBackForwardList mWebBackForwardList = webView.copyBackForwardList();
            String historyUrl = mWebBackForwardList.gereplacedemAtIndex(mWebBackForwardList.getCurrentIndex() - 1).getUrl();
            webView.goBack();
            SearchText.setText(historyUrl);
        }
    }

    private void forward() {
        if (webView.canGoForward()) {
            WebBackForwardList mWebBackForwardList = webView.copyBackForwardList();
            String historyUrl = mWebBackForwardList.gereplacedemAtIndex(mWebBackForwardList.getCurrentIndex() + 1).getUrl();
            webView.goForward();
            SearchText.setText(webView.getUrl());
        }
    }

    private clreplaced MyWebChromeClient extends WebChromeClient {

        Context context;

        public MyWebChromeClient(Context context) {
            super();
            this.context = context;
        }
    }

    private boolean isNeedGrantPermission() {
        try {
            if (IOUtils.hasMarsallow()) {
                if (ContextCompat.checkSelfPermission(this, REQUEST_PERMISSION) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, REQUEST_PERMISSION)) {
                        final String msg = String.format(getString(R.string.format_request_permision), getString(R.string.app_name));
                        AlertDialog.Builder localBuilder = new AlertDialog.Builder(MainActivity.this);
                        localBuilder.setreplacedle("Permission Required!");
                        localBuilder.setMessage(msg).setNeutralButton("Grant", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
                                ActivityCompat.requestPermissions(MainActivity.this, new String[] { REQUEST_PERMISSION }, REQUEST_PERMISSION_CODE);
                            }
                        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
                                paramAnonymousDialogInterface.dismiss();
                                finish();
                            }
                        });
                        localBuilder.show();
                    } else {
                        ActivityCompat.requestPermissions(this, new String[] { REQUEST_PERMISSION }, REQUEST_PERMISSION_CODE);
                    }
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        try {
            if (requestCode == REQUEST_PERMISSION_CODE) {
                if (grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 
                } else {
                    iUtils.ShowToast(MainActivity.this, getString(R.string.info_permission_denied));
                    finish();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            iUtils.ShowToast(MainActivity.this, getString(R.string.info_permission_denied));
            finish();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.gereplacedemId();
        if (id == R.id.nav_downloads) {
            startActivity(new Intent("android.intent.action.VIEW_DOWNLOADS"));
        } else if (id == R.id.nav_bookmarks) {
            Intent intent = new Intent(MainActivity.this, BookmarkActivity.clreplaced);
            startActivity(intent);
        } else if (id == R.id.nav_get_media) {
            GetMedia();
        } else if (id == R.id.nav_manage) {
            Intent intent = new Intent(MainActivity.this, SettingActivity.clreplaced);
            startActivity(intent);
        } else if (id == R.id.nav_share) {
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey check out best video downloader at: https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName());
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
        } else if (id == R.id.nav_send) {
            Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", EMAIL_ID, null));
            startActivity(Intent.createChooser(emailIntent, "Send email..."));
        } else if (id == R.id.nav_rate) {
            Uri uri = Uri.parse("market://details?id=" + MainActivity.this.getPackageName());
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            // To count with Play market backstack, After pressing back button,
            // to taken back to our application, we need to add following flags to intent.
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOreplacedENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            try {
                startActivity(goToMarket);
            } catch (ActivityNotFoundException e) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName())));
            }
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        // put your code here...
        AdblockEnabled = sharedPrefs.getBoolean("ADBLOCK", true);
        webView.onResume();
        webView.resumeTimers();
    }

    @Override
    public void onPause() {
        super.onPause();
        // put your code here...
        webView.onPause();
        webView.pauseTimers();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.loadUrl("about:blank");
        webView.stopLoading();
        webView.setWebChromeClient(null);
        webView.setWebViewClient(null);
        webView.destroy();
        webView = null;
    }
}

See More Examples