Android:Realm完成同步时如何处理?

时间:2017-08-16 14:00:27

标签: android realm

我想在启动Android应用时启动(在后台)与Realm Object Server同步。成功下载数据后,我想展示吐司。

我怎么能这样做?我需要使用什么方法? 感谢。

1 个答案:

答案 0 :(得分:2)

我没试过这个,但它应该有用。

private void setRealmDefaultConfiguration(SyncUser syncUser, String realmURL) {
    SyncConfiguration config = new SyncConfiguration.Builder(syncUser, realmURL)
            .waitForInitialRemoteData()
            .build();
    Realm.setDefaultConfiguration(config);
}

public abstract class BaseActivity extends Activity {
    private static boolean firstInit = true;

    protected Realm realm = null;

    @Override
    public void onCreate(Bundle bundle) {
        final boolean shouldShowToast;
        if(firstInit) {
            firstInit = false;
            shouldShowToast = true;
        } else {
            shouldShowToast = false;
        }
        super.onCreate(bundle);
        Realm.getInstanceAsync(Realm.getDefaultConfiguration(), new Realm.Callback() {
            @Override
            public void onSuccess(Realm realm) {
                if(isChangingConfigurations() || isFinishing()) {
                    realm.close();
                } else {
                    BaseActivity.this.realm = realm;
                    onRealmLoaded(realm);
                }
                if(shouldShowToast) {
                    Toast.makeText(BaseActivity.this, R.string.data.loaded, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onError(Throwable throwable) {
                // boop
            }
        });
    }

    protected void onRealmLoaded(Realm realm) {
        // override this if needed
    }
}