我已经更新到最新的 Android SDK 工具 (23.0.0)、平台工具 (20.0.0)、Android Studio Gradle 插件 (0.12.+),突然我收到一个奇怪的 Lint 问题报告,说我应该使用 apply() 而不是 commit() 因为 apply() 是异步的,并且将允许 UI 线程继续进行,因为 commit() 将阻止它进行写入。凉爽的。但我仍然得到这个:
这是一个 Lint 错误,还是我遗漏了什么?
显然我可以抑制这个警告,但我发现它毫无意义并且不知道根本原因。
编辑:从命令行构建应用程序时也会引发此问题。
最佳答案
这确实是一个 Lint 错误。更具体地说,this one .
错误似乎在SharedPrefsDetector
的CommitFinder
内部类中:
@Override
public boolean visitMethodInvocation(MethodInvocation node) {
...
String name = node.astName().astValue();
boolean isCommit = "commit".equals(name);
if (isCommit || "apply".equals(name)) {
...
if (returnValueIgnored) {
String message = "Consider using apply() instead; commit writes "
+ "its data to persistent storage immediately, whereas "
+ "apply will handle it in the background";
mContext.report(ISSUE, node, mContext.getLocation(node), message,
null);
}
我想这个想法是只有当你没有将 commit()
的返回值分配给任何东西时才发出这个警告(这部分有效),但是它们忘记检查 isCommit
标志。 :)
关于Android lint SharedPreferences.Editor.apply() 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24531270/