简体   繁体   中英

How to make `onResume` only be called when the activity comes to screen and not by other methods calling it

I have a situation with onResume() method and I don't know how to solve it. conssider the following code:

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle b) {
        super.onCreate(b);
        Log.d("tag", "onCreate");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //do something only when everytime the activity comes to screen
        Log.d("tag", "onResume");
    }

    private void myMethod() {
        this.onResume();
    }
}

If we asume that myMethod will definitly be called, I don't want to let onResume() to execute //do something only when everytime the activity comes to screen . I should note that myMethod is a fixed method and cannot be changed.

PS:The reason that I am asking this question is that I have a simillar situation with PermissionDispatcher library with android 6 and I want to call a "risky permission" in the onReume() method but if the user denies the permission, it will call the onReume() again, and since the permission required task is in the onResume() , the permission will be denied again and cauases an inifite loop

could anyone give me a suggestion?

UPDATE: here is the permissionDispatcher library and the issue that is related to my problem

verify this method Already Executed or not simply in if Condition

Bool a=true;

     @Override
            protected void onResume() {
                super.onResume();
                //do something only when everytime the activity comes to screen
                if(a==true)
                   {
                   //your Actions 
                    }
        else if(a==false)
        {
        //do nothing 
        }
            }

Use SharedPreferences in onResume

@Override
protected void onResume() {
    super.onResume();
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean firstStart = settings.getBoolean("firstStart", true);
   if(firstStart) {
    //do something only when everytime the activity comes to screen
    Log.d("tag", "onResume");
    //display your Message here
     SharedPreferences.Editor editor = settings.edit();
     editor.putBoolean("firstStart", false);
     editor.commit();
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM