简体   繁体   中英

How to use onWindowFocusChanged() method?

I am confused in how to trigger an event when the activity is changed. One thing that I know is using onWindowFocusChanged() method but I don't know how to use it. Please help in one example ie when the activity changes, it should show a toast said "Activity changed".

The following method gets called when window's focus changes. For instance, if the window gains/losses focus, it will be triggered. In case, the window gains focus, hasFocus is true and false otherwise.

 public void onWindowFocusChanged(boolean hasFocus) {         
     super.onWindowFocusChanged(hasFocus);
     if(hasFocus) 
         Toast.makeText(context, text, duration).show();
 }
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if(!hasFocus) {
            //do anything you want here
            Toast.makeText(MainActivity.this,"Activity changed",Toast.LENGTH_SHORT).show();
        }
    }

}

This might help...

Called when the current Window of the activity gains or loses focus. This is the best indicator of whether this activity is visible to the user. The default implementation clears the key tracking state, so should always be called.

@Override
public void onWindowFocusChanged(boolean hasFocas) {
    super.onWindowFocusChanged(hasFocas);
    //your code here
}

hasFocus boolean: Whether the window of this activity has focus.

Android 10 brought restrictions on apps accessing the clipboard. Now, only the app that currently has focus can access the clipboard.

Previously, you might be accessing this data in onResume, but on Android 10 this doesn't work. Instead, you can wait until the view is laid out using onWindowFocusChangedcallback.

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