Android,在Application中使用Realm singleton

Tax*_*Noi 6 android realm

我是Realm的新手,我想知道在Application对象中只有一个Realm实例是好的做法,在应用程序中需要的所有情况下使用它,并且只onDestroy在Application类中关闭它.

谢谢

Chr*_*ior 10

将Realm保持在UI线程打开而不关闭它本身没有任何错误(注意没有OnDestroy打开Application)

但是,您应该记住以下几点:

1)Realm可以处理被杀的过程,这意味着忘记关闭Realm对你的数据没有危险.

2)当应用程序进入后台时不关闭Realm意味着如果资源不足,您将更有可能被系统杀死.

正如埃马努埃莱所说.领域内部使用线程本地缓存,以便不打开超出需要的领域.这意味着你不应该关心你调用多少次,Realm.getInstance()因为在大多数情况下它只是一个缓存查找.然而,总是有一个相应的close方法是很好的做法.

// This is a good pattern as it will ensure that the Realm isn't closed when
// switching between activities, but will be closed when putting the app in 
// the background.
public class MyActivity extends Activity {

    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      realm = Realm.getDefaultInstance();
    }

    @Override
    protected void onDestroy() {
      realm.close();
    }
}
Run Code Online (Sandbox Code Playgroud)