一次调用方法

时间:2013-11-22 17:09:51

标签: java android methods

我遇到了一个问题,即如果条件达到多次就会调用一次方法!例如:

public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times
  if(somethingHappened){

       callAMethodOnce();// this method is called once even if the condition achieved again
  }

}

请帮忙解决

5 个答案:

答案 0 :(得分:3)

public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times
  if(somethingHappened){

       if (!isAlreadyCalled){   
           callAMethodOnce();// this method is called once even if the condition achieved again
           isAlreadyCalled = true;
       }
  }

}

答案 1 :(得分:3)

boolean isHappendBefore = false;

public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times

  if(somethingHappened && (! isHappendBefore) ){
       isHappendBefore = true;
       callAMethodOnce();// this method is called once even if the condition achieved again
  }

}

答案 2 :(得分:1)

你可以简单地设置一个标志。如果您只需要对Activity的每个实例进行一次,则设置成员变量。

public class MyActivity extends Activity
{
     boolean itHappened = false;

     ...

    public void onLocaitonChanged(Location location)
   {

      // this if statement may achieve the condition many times
      if(somethingHappened && !itHappened)
      {
           callAMethodOnce();// this method is called once even if the condition      achieved again
           itHappened = true;
      }   
   }

如果您希望它只在应用程序的生命周期中发生一次,那么将该变量设置为SharedPreference

答案 3 :(得分:1)

设置类宽布尔值

if(!hasRun){
    callAMethodOnce();
    hasRun = true;
}

答案 4 :(得分:1)

也许我没有正确理解你的问题但是根据你的问题定义,我建议使用类似的布尔变量。

boolean run = false;
public void onLocaitonChanged(Location location){

  // this if statement may achieve the condition many times
  if(somethingHappened && run == false){
        run = true;
       callAMethodOnce();// this method is called once even if the condition achieved again
  }

}

一旦if语句下的代码执行runtrue且后续调用callAMethodOnce()