Search code examples
androidandroid-fragmentsfragmentpageradaptergoogle-fit

How can a fragment not be reset when not on screen?


I'm developing an android application (for Marshmallow at least) using Android Studio on Windows 10. My app was created using the tabbedActivity template provided by Android Studio. Which means it contains a mainActivity containing a fragmentPagerAdapter launching fragment for each tab and keeping them in memory.

What my app looks like

enter image description here

What I want to do:

This app is supposed to be a sport app. On the "Run" tab you can see on the link above, I connect to the Google fit API and subscribe to some DataTypes. The floatingActionButton gives you the opportunity to start an activity (running in this case), which will start a session, connect to the sensors and display stuff while you run.

I would like the user to be able to go to another tab while he is running. When he goes back to the "Run" tab, everything should still be recording and displaying.

What the problem is:

For some reason, sometimes it works, sometimes not. It seems to be working if I try to switch to 1 or 2 tabs and come back. But when I do too many tab switch, there's a little freeze, a few logs displaying in Logcat and the "Run" tab is reset to 0 when I come back.

The logs:

Skipped 90 frames! The application may be doing too much work on its main thread. D/InputTransport: Input channel constructed: fd=145 D/ViewRootImpl@fcb463d[Toast]: setView = android.widget.LinearLayout{921ae32 V.E...... ......I. 0,0-0,0} touchMode=true D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [697x132]-format:1 I/System.out: mExitValue 0 D/ViewRootImpl@fcb463d[Toast]: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1 I/System.out: (HTTPLog)-Static: isSBSettingEnabled false I/System.out: (HTTPLog)-Static: isSBSettingEnabled false I/System.out: (HTTPLog)-Static: isSBSettingEnabled false I/System.out: (HTTPLog)-Static: isSBSettingEnabled false D/ViewRootImpl@fcb463d[Toast]: dispatchDetachedFromWindow Input channel destroyed: fd=145

If you have any solutions help would be greatly appreciated!


Solution

  • After additional researches, I found that it was possible to increase the number of off-screen pages which is 1 by default when using a viewpager: https://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)

    mViewPager.setOffscreenPageLimit(4);
    

    Setting it to 4 will make the viewpager keep in memory 4 tabs (+ the one being displayed). Moreover, it makes the swipe animation way smoother with no small freezes anymore.