Is the Activity being destroyed because orientation changed or because app is closing?

后端 未结 6 1317
面向向阳花
面向向阳花 2021-01-01 21:12

I have an Activity that starts an AsyncTask. The activity is allowed to show in Portrait or Landscape orientation. When the orientation is

6条回答
  •  天涯浪人
    2021-01-01 22:14

    The best way I found after some research was to create an application class and rely on onTrimMemory() method. A problem with this approach - onTrimMemory() does not get called if screen times out or screen gets locked by pressing power button so I had to implement that logic separately.

    /**
     * When your app's process resides in the background LRU list:
     * TRIM_MEMORY_BACKGROUND
     * TRIM_MEMORY_MODERATE
     * TRIM_MEMORY_COMPLETE
     *
     * When your app's visibility changes:
     * TRIM_MEMORY_UI_HIDDEN
     */
    @Override
    public void onTrimMemory(final int level) {
        super.onTrimMemory(level);
        if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
                || level == ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
                || level == ComponentCallbacks2.TRIM_MEMORY_COMPLETE
                || level == ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
    
            // App went in background
    
        }
    }
    

    Following code is to detect screen lock. I implemented this code in one of the ActivityLifecycleCallbacks method - onActivityStopped()

    final PowerManager powerManager = (PowerManager) getAppContext().getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
        if (!powerManager.isScreenOn()) {
            // Screen locked
        }
    } else {
        if (!powerManager.isInteractive()) {
            // Screen locked    
        }
    }
    

提交回复
热议问题