首页 > 解决方案 > SharedPreferences 不保存值

问题描述

由于某种原因 SharedPreferences 不保存值,代码在服务中......

    Thread thread = new Thread() {
        public void run() {
            SharedPreferences sharedPref = getBaseContext().getSharedPreferences(getString(R.string.not_local_sp), MODE_PRIVATE);
            long lastExecuted = sharedPref.getLong(getString(R.string.timeDone), 0L);
            int scanInterval = 500 * 60 * 60;

            while (true) {
                if (System.currentTimeMillis() - lastExecuted >= scanInterval && contextCreator == null) {
                    Log.d(TAG, "inside while loop");
                    Log.d(TAG, String.valueOf(System.currentTimeMillis() - lastExecuted));
                    Log.d(TAG, String.valueOf(lastExecuted));
                    Log.d(TAG, String.valueOf(scanInterval));
                    contextCreator = new ProtectionContextCreator();
                    feature = AppScanFactory.createAppScan(getBaseContext());
                    feature.add(new BoostFeature(getBaseContext(), new StubScanStore()));
                    contextCreator.create(getBaseContext(), feature.getType(), NotificationService.this);

                    /*Shared pref*/

                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putLong(getString(R.string.timeDone), System.currentTimeMillis());
                    editor.commit();
                }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    thread.start();

lastExecuted 变量始终获得默认值 0。

标签: androidmultithreadingsavesharedpreferences

解决方案


您有一个无限循环 ( while(true)) 但您正在读取它之外的值

这条线

long lastExecuted = sharedPref.getLong(getString(R.string.timeDone), 0L)

应该在 while 循环内(如果您lastExecuted用于检查值是否已存储)


推荐阅读