简体   繁体   中英

Clearing an EditText when the recent apps button is pressed

I want to clear the edit text which is basically a password field when app goes to background or when recent apps button in menu is pressed.

I do this way -

@Override
public void onPause() {
    super.onPause();
    if (password != null) {
        password.getText().clear();
    }
}

But my problem is when the recent apps button in menu is pressed, the app goes to half background and I can see the password still. How do I clear it in this scenario?

Do the above code inside onStop() , onPause() , onDestroy() ie all the possibe functions that android can call when the app goes in background.

Many times onStop() method is called instead of onPause()

None of standard Activity Lifecycle methods is called when "Recent Apps" button pressed. Activity will stay active after list of recent apps popups.

The only Activity method are getting called when user opens "Recent Apps" list (or returns from it) is onWindowFocusChanged with boolean parameter hasFocus . When user open list of Recent App method onWindowFocusChanged() called with hasFocus equals false , and same method called with hasFocus equals true when user pressing Back in this list.

Try below code,

public void onWindowFocusChanged(boolean hasFocus) {         
    super.onWindowFocusChanged(hasFocus);
    if(!hasFocus && password != null) {
        password.setText("");
    }
}

But my problem is when the recent apps button in menu is pressed, the app goes to half background and I can see the password still. How do I clear it in this scenario?

As the official documentation says:

onPause() execution is very brief, and does not necessarily afford enough time to perform save operations. For this reason, you should not use onPause() to save application or user data, make network calls, or execute database transactions; such work may not complete before the method completes. Instead, you should perform heavy-load shutdown operations during onStop()

So you should move the code to onStop()

And if you wanna know how and why kindly check: https://developer.android.com/guide/components/activities/activity-lifecycle

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