设置警报对话框之间的时间

时间:2014-02-24 15:41:35

标签: android alertdialog

当用户退出某个区域时,我会显示警告:

   /*Function to show alert when Geofence breached*/
   private void showAlert() {
       final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Geofence Breached");
        builder.setMessage("User has breached the Geofence Boundary!");
        builder.setPositiveButton(android.R.string.ok, null);
        builder.show();
    }

我这样称呼它:

 if( distance[0] > mCircle.getRadius()  ){                      
     showAlert();

}

是否有任何方法可以将警报设置为每2分钟一次,因为始终会检查位置,然后通知会一直显示。我读过,Timers,Timertasks和alarmManagers,但我不认为它对我有用。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

在您的活动/服务中有一个成员变量来记录上次显示该对话框的时间:

long timeDialogShown = 0;

检查是否显示对话框时,将现在的时间与上次显示对话框的时间进行比较。如果超过2分钟,或者之前从未显示过,请显示对话框并更新时间戳。否则就什么都不做。

if( distance[0] > mCircle.getRadius() )
{
    long timeNow = System.currentTimeMillis()/1000;  //Timestamp in seconds
    if ( (timeNow - timeDialogShown) > 120 || timeDialogShown == 0)  //Show if 2 minutes have passed
    {
        timeDialogShown = System.currentTimeMillis()/1000; //Timestamp in seconds
        showAlert();
    }
}

答案 1 :(得分:0)

在这里,先生。

final AlertDialog dialog = ....
new Handler().postDelayed(new Runnable() 
{
  public void run() 
  {
    dialog.dismiss();
  }
}, 1000 * 60 * 2);

它会在2分钟(1000毫秒* 60秒* 2分钟)后关闭对话框

答案 2 :(得分:0)

见到这一点 - https://stackoverflow.com/a/6203816/881771 你需要在对话框上设置一个dismiss监听器,它会阻止你的showDialog()方法2分钟。

  1. 维护一个布尔值,表明自上次警报显示/解除后是否已经过了两分钟。

    boolean twoMinsElapsed = true;

  2. 在显示alertDialog的代码中,检查此布尔值

    if (distance[0] > mCircle.getRadius() && twoMinsElapsed) {
               //block the showDialog() method until this value is set to true again
                twoMinsElapsed=false;
                showDialog();
            }
    
  3. 为alertdialog设置dismisslistener

    alertDialog.setOnDismissListener(new OnDismissListener(){

        @Override
        public void onDismiss(DialogInterface dialog) {
            new Handler().postDelayed(new Runnable() {
    
                @Override
                public void run() {
                   //Set this boolean value back to true. will be called after two mins
                    twoMinsElapsed= true;
                }
    
            }, 120000);
    
        }
    });
    
  4. 将此视为伪代码:)

相关问题