2013-11-22 94 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 
    } 

}