简体   繁体   中英

How to maintain a variable throughout different activities and not use shared preferences

I want to keep track of a variable through different Activities, but I don't want to use Shared Preferences .

I can have a class with a static variable and static methods, but when the application is closed and opened again I lose the data.

// Data lost when app is closed.
public class DataHolder
{
    static boolean isDone = false;

    public static boolean isDone()
    {
        return isDone;
    }

    public static void setIsDone(boolean done)
    {
        isDone = done;
    }
}

How can I persist data while my device is on?

Basically I want my data to stay active until I reboot the device.


I don't want to use Shared Preferences because data has to reset the moment I reboot. And I don't think I can catch a reboot to clear data. I guess I could clear the Shared Preferences when BOOT_COMPLETED , but maybe someone has a better idea.

As far as I know save your data to a persistent storage is good answer for your question. Let's use SharedPreferences and BOOT_COMPLETED as you said.

您可以使用数据库来保存数据,给您带来不便吗?

You can use static variable. but it will destroy once your application destroy completely otherwise it will work fine, throughout the application

Android's Application Object could replace your DataHolder Object.

Class description

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's <application> tag, which will cause that class to be instantiated for you when the process for your application/package is created.

有3种方式将数据存储在android 1.SharedPreference 2.database 3.File中的持久性存储中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM