簡體   English   中英

SharedPreferences不保存值

[英]SharedPreferences doesn't save values

由於某些原因,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。

您有一個無限循環( while(true) ),但您正在讀取其外部的值

這條線

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

應該在while循環內(如果您使用lastExecuted檢查值是否已存儲)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM