Ich habe ein Problem, wie eine Methode einmal aufgerufen wird, wenn die Bedingung viele Male erreicht wird! zum Beispiel:
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
}
}
Bitte helfen Sie dabei
Antworten:
3 für die Antwort № 1public 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;
}
}
}
3 für die Antwort № 2
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
}
}
1 für die Antwort № 3
Sie können einfach eine Flagge setzen. Wenn Sie es nur brauchen, nur einmal mit jeder Instanz von Activity
Legen Sie dann eine Mitgliedsvariable fest.
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;
}
}
Wenn Sie möchten, dass es nur einmal im Leben der Anwendung geschieht, setzen Sie diese Variable als SharedPreference
1 für die Antwort № 4
setze eine Klasse breit boolean
if(!hasRun){
callAMethodOnce();
hasRun = true;
}
1 für die Antwort № 5
Vielleicht verstehe ich Ihre Frage nicht richtig, aber aus Ihrer Problemdefinition würde ich vorschlagen, eine boolesche Variable zu verwenden.
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
}
}
Einmal den Code unter if
Anweisung wird einmal ausgeführt run
wäre true
und es wird keine nachfolgenden Anrufe geben callAMethodOnce()