Android 弹出窗口 定时关闭

时间:2022-04-27 02:34:39

       工作中正需要一个弹出窗口的定时关闭,考虑了下可以使用Handler,Timer或者AsyncTask基础结合实现。不过,偶然发现了原来Android的api竟然已有类似功能的实现类CountDownTimer。该类实现了在指定时间间隔进行倒计时功能。

 查看Android的SDK,看到该类

public abstract class

CountDownTimer

extends Object
java.lang.Object
   ↳ android.os.CountDownTimer

是一个抽象类运行在应用的子线程主要的方法:

  public abstractvoid onFinish() { }
  public abstract void onTick(long millisUntilFinished)

尽管CountDownTimer类是运行在应用的子线程,但上面实现的两个方法却是运行在主线程的。效果图:


Android 弹出窗口 定时关闭

下面上代码:


public class CountDownDialog 
{
private Activity _activity;
private LayoutInflater _inflater;
private View _layout;
private View _anchor;
private TextView tv_tips;

private PopupWindow _popupWindow;
private CountTimer countTimer;

/**
* 构造函数
* @param activity上下文对象
* @param anchor 锚点
* @param millisInFuture 倒计的时间数,以毫秒为单位
* @param countDownInterval 倒计每秒中间的间隔时间,以毫秒为单位
*/
public CountDownDialog(Activity activity,View anchor,long millisInFuture, long countDownInterval)
{
_activity = activity;
_anchor = anchor;
_inflater = (LayoutInflater) _activity.getSystemService("layout_inflater");
_layout = (LinearLayout) _inflater.inflate(R.layout.count_dialog, null, true);
tv_tips = (TextView)_layout.findViewById(R.id.tv_countdialog_tips);
countTimer = new CountTimer(millisInFuture,countDownInterval);
}

public void show()
{
if(_popupWindow == null)
{
_popupWindow = new PopupWindow(_layout,250, 200,true);
}
_popupWindow.showAtLocation(_anchor, Gravity.CENTER, 0, 0);
_popupWindow.update();
countTimer.start();
}

public void cancle()
{
if(_popupWindow != null && _popupWindow.isShowing())
{
countTimer.cancel();
_popupWindow.dismiss();
if(_activity != null)
{
_activity.finish();
}
}
}

class CountTimer extends CountDownTimer
{

/**
* 构造函数
* @param millisInFuture 倒计的时间数,以毫秒为单位
* @param countDownInterval 倒计每秒中间的间隔时间,以毫秒为单位
*/
public CountTimer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}

@Override
public void onFinish()
{
cancle();
}

@Override
public void onTick(long millisUntilFinished)
{
tv_tips.setText(_activity.getString(R.string.issaving)+millisUntilFinished / 1000 + _activity.getString(R.string.second));
}

}

}