在单独的线程上访问 SharedPreferences

t3r*_*rse 1 multithreading android sharedpreferences

如果您使用应用,在单独的线程中编辑共享首选项是多余的吗?

我在 MainActivity 的 onCreate 方法中有以下代码块:

    final MainActivity activityReference = this;

    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {

            // if it is the first time running
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activityReference);
            if(!prefs.getBoolean(MainActivity.FIRST_LOAD, false)) {

                // enable a setting on first run                    

                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean(MainActivity.FIRST_LOAD, true);
                editor.apply();
            }

        }
    });
Run Code Online (Sandbox Code Playgroud)

因为 SharedPreferences.Editor 的实例正在调用 apply 方法,它应该是异步的,但在单独的线程中运行之前,我们仍然会违反严格模式。违规是 StrictModeDiskRead 违规,因此假设它们是由于获取 SharedPreferences 而不是调用 apply 导致的。此外,似乎三星设备几乎完全有这个问题。

Com*_*are 5

如果您使用应用,在单独的线程中编辑共享首选项是多余的吗?

是的,但请记住,您可能不仅要编辑SharedPreferences. 您可能也在阅读它们。

鉴于您的代码的性质,我的猜测是您将其称为LAUNCHER活动中的第一件事。如果是这样,则还没有其他任何东西检索到它们SharedPreferences,因此您将从以下位置获得磁盘读取违规StrictMode,而不是编辑。

由于您已经拥有后台线程,因此我会切换到commit()而不是使用apply()并浪费另一个线程。