2013-11-22 51 views
-1

我遇到了一个问题,当条件达到很多次时,如何调用一次方法!例如:调用方法一次

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 
    } 

} 

请与

回答

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; 
     } 
    } 

} 
+2

考虑一下,如果多线程使用'AtomicBoolean'。 –

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

1

设置一类广泛布尔

if(!hasRun){ 
    callAMethodOnce(); 
    hasRun = true; 
} 
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()

+0

运行应该在onLocaitonChanged之外 –

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 
    } 

}