在Android的应用程序,使用单境界 [英] Android, using Realm singleton in Application

查看:105
本文介绍了在Android的应用程序,使用单境界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的领域,我不知道它是否是很好的做法,只是在申请对象中一个领域实例,在整个应用程序所需的所有情况下使用它,只有关闭它在的onDestroy Application类的。

I'm new to Realm, I'm wondering whether it's good practice to just have one Realm instance in Application object, use it across all cases needed in the app, and only close it in onDestroy of the Application class.

感谢

推荐答案

有什么内在的错误保持UI线程上境界开阔,而不是将其关闭(注意有没有的OnDestroy 应用

There is nothing inherently wrong with keeping the Realm on the UI thread open and not closing it (note there is no OnDestroy on Application)

然而,你应该记住以下几点:

However you should keep the following in mind:

1)域可以处理的过程中被杀就好了,这意味着忘记关闭境界是没有危险的数据。

1) Realm can handle the process getting killed just fine, which means that forgetting to close Realm is not dangerous to your data.

2)不关闭境界时,应用程序转到后台意味着你将更有可能得到由系统终止。如果它得到资源不足。

2) Not closing Realm when the app goes in the background means you will be more likely to get killed by the system if it gets low on resources.

由于埃马努埃莱说。内部以不打开更多的领土比需要的领域使用线程本地高速缓存。这意味着,你不应该关心你多少次调用 Realm.getInstance()因为在大多数情况下,这将只是一个缓存查找。这不过是很好的做法,始终有一个对应的关闭方法为好。

As Emanuele said. Realm use thread local caches internally in order to not open more Realms than needed. This means that you shouldn't care how many times you call Realm.getInstance() as in most cases it will just be a cache lookup. It is however good practise to always have a corresponding close method as well.

// 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();
    }
}

这篇关于在Android的应用程序,使用单境界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆