安装包 io.realm
类 Realm.Callback
- java.lang.Object
-
- io.realm.BaseRealm.InstanceCallback< Realm >
-
- io.realm.Realm.Callback
-
- 封装类:
- Realm
public abstract static class Realm.Callback extends io.realm.BaseRealm.InstanceCallback<Realm>
在报告使用Realm.getInstanceAsync(RealmConfiguration, Realm.Callback)
或DynamicRealm.getInstanceAsync(RealmConfiguration, DynamicRealm.Callback)
异步加载 Realm 的结果时使用的回调。在进程中创建第一个 Realm 实例之前,需要完成一些初始化工作,例如创建或验证模式、需要时运行迁移、复制资产文件(如果提供了
RealmConfiguration.Builder.assetFile(String)
)以及执行RealmConfiguration.Builder.initialData(Realm.Transaction)
如果需要)。 此工作可能需要一些时间,并会阻塞调用者线程一段时间。 为避免getInstance()
阻塞主线程,可以改用getInstanceAsync()
在背景线程中执行初始化工作,并将 Realm 实例传递给调用者线程。一般来说,此方法在用户界面线程上最有用,因为应尽可能少地阻止该线程。 在任何其他事件循环线程或其他不支持回调的线程上,使用标准
getInstance()
应该没问题。以下是在应用程序启动第一个 Activity 时使用
getInstanceAsync()
的示例:public class MainActivity extends Activity { private Realm realm = null; private RealmAsyncTask realmAsyncTask; private static RealmConfiguration config = new RealmConfiguration.Builder() .schema(42) .migration(new MyMigration()) // Potentially lengthy migration .build(); \@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); realmAsyncTask = Realm.getInstanceAsync(config, new Callback() { \@Override public void onSuccess(Realm realm) { if (isDestroyed()) { // If the activity is destroyed, the Realm instance should be closed immediately to avoid leaks. // Or you can call realmAsyncTask.cancel() in onDestroy() to stop callback delivery. realm.close(); } else { MainActivity.this.realm = realm; // Remove the spinner and start the real UI. } } }); // Show a spinner before Realm instance returned by the callback. } \@Override protected void onDestroy() { super.onDestroy(); if (realm != null) { realm.close(); realm = null; } else { // Calling cancel() on the thread where getInstanceAsync was called on to stop the callback delivery. // Otherwise you need to check if the activity is destroyed to close in the onSuccess() properly. realmAsyncTask.cancel(); } } }