SharedPreferences不保存值

时间:2018-11-08 13:00:46

标签: android multithreading save 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。

1 个答案:

答案 0 :(得分:0)

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

此行

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

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