Calling a Method Once [closed]

2019-09-20 18:17发布

I am having a problem of how to call a method once when the condition achieves many times! for example:

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
  }

}

Please help with that

5条回答
霸刀☆藐视天下
2楼-- · 2019-09-20 18:32
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;
       }
  }

}
查看更多
你好瞎i
3楼-- · 2019-09-20 18:47
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
  }

}
查看更多
不美不萌又怎样
4楼-- · 2019-09-20 18:52

Maybe I don't understand your question correctly but from your problem definition I would suggest using a boolean variable something like.

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
  }

}

Once the code under if statement gets executed once run would be true and there won't be any subsequent calls to callAMethodOnce()

查看更多
Fickle 薄情
5楼-- · 2019-09-20 18:54

You could simply set a flag. If you just need it to only happen once with each instance of the Activity then set a member variable.

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

If you want it to only happen once ever in the life of the application then set that variable as a SharedPreference

查看更多
Luminary・发光体
6楼-- · 2019-09-20 18:58

set a class wide boolean

if(!hasRun){
    callAMethodOnce();
    hasRun = true;
}
查看更多
登录 后发表回答