保持对象为onPause()

时间:2018-09-19 11:56:59

标签: java android android-fragments

我在使用Android Fragments时遇到很多麻烦,我不知道为什么。

每当我暂停应用程序(onPause())时,我都希望将对象保留在内存中。

我有一个带有某些图层的MapView。而且我想保留这些图层,所以不必在我暂停和恢复应用程序时从头重新加载并重新创建地图。

问题是,我无法使用onSaveInstanceState()保存它们。它们是对象,而不是基元。它们也来自库,所以我不能使它们实现Serializable或Parcelable。

我想找到一种不求助于解决方案的解决方案:

android:configChanges="orientation|screenSize">

“我的活动”,因为这被认为是不良做法。另外,当您暂停并恢复应用程序时,该功能也将不起作用。

我也尝试过

this.setRetainInstance(true); // retain this fragment

在我片段的onCreate()上,但是我也想避免它。反正还是行不通的。

经过大量的尝试,错误和测试,我发现我片段的onSaveInstanceState()甚至没有运行。每当我暂停并恢复应用程序时,我什至都不能保留一个简单的布尔值。

我读到

Saving Android Activity state using Save Instance State

https://developer.android.com/training/basics/activity-lifecycle/recreating

savedInstanceState is always null

取消许多其他帖子,当然还有Android文档。

我的一些代码:

创建片段:

    navFragment = FragNavigation.newInstance(); // keeping the reference to the navFragment

    // setting up the viewpager
    ViewPager viewPager = findViewById(R.id.vpMainViewPager);
    MainPagerAdapter mainAdapter = new MainPagerAdapter(getSupportFragmentManager(), this);
    mainAdapter.addFragment(navFragment);
    viewPager.setAdapter(mainAdapter);

尝试以实例状态保存一个简单的布尔值(请记住:这甚至没有运行):

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);

    Log.e(TAG, "onSaveInstanceState: is map loaded? " + mapIsLoaded );

    outState.putBoolean("mapIsLoaded", mapIsLoaded);
}

并尝试加载它:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRetainInstance(true); // retain this fragment

    Log.e(TAG, "onCreate: null? " + (savedInstanceState == null) );

    if (savedInstanceState != null)
        mapIsLoaded = savedInstanceState.getBoolean("mapIsLoaded", false);
}

我想念什么?我显然不明白。为什么在暂停应用程序时保留值如此困难?

2 个答案:

答案 0 :(得分:1)

我建议根据体系结构组件,使用ViewModel存储MapView图层。如果不是这样,则可以使用“活动” getLastNonConfigurationInstance手动存储和检索对象。

答案 1 :(得分:0)

 @Override
    public void onPause() {
        /**
         * store your data 

         */

        super.onPause();
    }

    @Override
    public void onResume() {
        /**
         * retrieve your data       
         */



        super.onResume();
    }