感谢@ast 代码示例。我还通过缓存命令模式解决了这个问题,这是我的代码:
public class CommandPattern extends RealmObject {
@PrimaryKey
private String id;
private String commandName;
public String getCommandName() {
return commandName;
}
public void setCommandName(String commandName) {
this.commandName = commandName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_increment:
if (isOnline()) {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
updateNumberOnRealm();
}
});
realm.close();
} else {
addMethodToCache("increment");
}
public void addMethodToCache(final String methodName) {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
commandPattern = new CommandPattern();
commandPattern.setId(UUID.randomUUID().toString());
commandPattern.setCommandName(methodName);
realm.copyToRealmOrUpdate(commandPattern);
}
});
realm.close();
}
public void invokeCachedCommands() {
realm = Realm.getDefaultInstance();
commandsCached = realm.where(CommandPattern.class).findAll();
commandsCached.addChangeListener(new RealmChangeListener<RealmResults<CommandPattern>>() {
@Override
public void onChange(final RealmResults<CommandPattern> element) {
if(!element.isEmpty()) {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (CommandPattern command : element) {
if(command != null) {
if (command.getCommandName().equals("increment")) {
//updateNumberOnRealm();
RealmResults<Number> results = realm.where(Number.class).findAll();
results.get(0).increment();
command.deleteFromRealm();
}
}
}
}
});
}
}
});
realm.close();
}
在完成增量操作之前,我检查联机状态,如果它处于脱机状态,则在再次联机后缓存在命令模式对象中的增量字符串通过以下代码调用这些缓存的命令:
IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
if (isNetworkAvailable) {
invokeCachedCommands();
}else{
if(commandsCached != null) {
commandsCached.removeChangeListeners();
}
}
}
}, intentFilter);
这是通用的自定义冲突解决方案,可用于任何类型的命令