![](/img/trans.png)
[英]What gets called when the screen changes orientation? My app is restarting when I change orientations
[英]SharedPref does not save changes when restarting app
这是一个很好的开始。 我有一种情况,我需要在清除共享首选项后重新启动应用程序,所以这就是我要做的
sp.edit().clear().apply();
Intent mStartActivity = new Intent(context, IntroActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
但是当我刚使用时它清除了sp
sp.edit().clear().apply();
然后继续手动重新启动应用程序,有人可以向我解释如何解决此问题,这样我可以自动重新启动应用程序而无需用户手动进行操作?
使用commit()
而不是apply()
。
与commit()将其首选项同步写到持久性存储中的方式不同,apply()立即将其更改提交到内存中的SharedPreferences,但是将异步提交到磁盘,并且不会收到任何故障通知。 如果此SharedPreferences上的另一个编辑器在apply()仍未完成的情况下执行常规commit(),则commit()将阻塞,直到所有异步提交以及提交本身都完成为止。
像文档状态一样, apply()
是异步的,可能不会立即启动。 如果调用它,然后立即终止进程,则没有时间实际保存对磁盘所做的更改。
另一方面, commit()
将阻塞当前线程,直到操作完成为止,确保System.exit(0)
不会中断它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.