android的生命周期,Android生命周期工具类,Android倒计时工具类

 2023-09-23 阅读 21 评论 0

摘要:多谢touch_ping的回应. 原来api有这个类 android.os.CountDownTimer, 具体实现很下面的差不多.import android.content.Context;import android.os.Handler;/*** Created by wangxingsheng on 16/7/11.*/public class CalculatorUtil {private Context mContext;public Calcul

多谢touch_ping 的回应.  原来api有这个类  android.os.CountDownTimer , 具体实现很下面的差不多.

import android.content.Context;

import android.os.Handler;

/**

* Created by wangxingsheng on 16/7/11.

*/

public class CalculatorUtil {

private Context mContext;

public CalculatorUtil(Context context){

mContext = context;

}

public void startTimer(final int delay,final OnOverListener listener){

final Handler handler = new Handler(mContext.getMainLooper());

Runnable runnable = new Runnable(){

private int count = 0;

@Override

public void run() {

count++;

if(count < delay){

listener.onTick(delay - count);

handler.postDelayed(this,1000);

}else{

listener.onOver();

}

}

};

handler.post(runnable);

}

public interface OnOverListener{

void onOver();//数字跳到0时调用此方法

void onTick(int tick);//第一次调用为总数 - 1,最后一次调用是1

}

}

这段程序可能存在问题(例如handler生命周期丶线程继续运行等因素导致的问题),因为用途简单 没有深究.欢迎提出问题

上面的代码没有停止功能,下面是改善之后的代码.

import android.content.Context;

import android.os.Handler;

/**

* Created by wangxingsheng on 16/7/11.

*/

public class CalculatorUtil {

private Context mContext;

private boolean requestStop;

private Handler handler;

private int mDelay;

private OnOverListener mListener;

public CalculatorUtil(Context context,int delay,OnOverListener listener){

mContext = context;

handler = new Handler(mContext.getMainLooper());

mDelay = delay;

mListener = listener;

}

public void startTimer(){

requestStop = false;

handler.post(runnable);

}

private Runnable runnable = new Runnable(){

private int count = 0;

@Override

public void run() {

if(requestStop){

return;

}

count++;

if(count < mDelay){

mListener.onTick(mDelay - count);

handler.postDelayed(runnable,1000);

}else{

mListener.onOver();

}

}

};

public void stopTimer(){

requestStop = true;

handler.removeCallbacks(runnable);

}

public interface OnOverListener{

void onOver();//数字跳到0时调用此方法

void onTick(int tick);//第一次调用为总数 - 1,最后一次调用是1

}

}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/88323.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息