首页 > 解决方案 > 用于连续存储数据的 Android 共享首选项

问题描述

我正在学习安卓。我对共享首选项文件有疑问。

我创建了一个前台服务。服务递增计数变量,该变量初始化为 0。

每当服务被销毁并重新启动时,count 变量就会再次从 0 开始。但是,我想从以前的值开始。所以,我必须将它存储在本地。

这是 onStartCommand() 方法。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    startForeground(NOTIFICATION_ID, displayNotification());

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {

                //I have to store this count value
                count++;

                sharedPrefEditor.putInt("COUNT_NUMBER", count);

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

我将计数值存储在共享首选项文件中。

在这种情况下,共享偏好是最好的吗?还是有更好的方法来做到这一点?

我可以将计数变量设为静态并将其值存储在 onDestroy() 方法的共享首选项文件中,但不能保证调用 onDestroy()。

我的要求是我必须在服务被销毁时存储计数值。这个怎么做?

标签: android

解决方案


推荐阅读