保存首选项在 Android 中引发异常

Saving Preferences throws exception in Android

我正在尝试使用以下代码在 Android 中保存用户首选项:

import java.util.prefs.Preferences;

class MyClass {
    void save() throws Exception {
        _prefs.put("NAME","VALUE");
        _prefs.flush(); // Throws exception
    }
    private final Preferences _prefs = Preferences.userNodeForPackage(MyClass.class);
}

...但是“刷新”调用生成以下异常:

W/java.util.prefs: Could not lock User prefs.  Unix error code 2.
W/System.err: java.util.prefs.BackingStoreException: Couldn't get file lock.

我猜是权限问题。所以我将以下内容添加到 AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

但我仍然遇到异常。

如何使用 java.util.prefs.Preferences class 在 Android 中保存用户首选项?

阅读一些doc,尤其是警告部分

On Android, the Preference nodes corresponding to the "system" and "user" preferences are stored in sections of the file system that are inaccessible to apps. Further, allowing apps to set "system wide" preferences is contrary to android's security model.

而不是 Preferences 使用 SharedPreferences,关于 HERE

中的一些文档