Shared Preferences are suddenly initialized at some point.

Asked 2 years ago, Updated 2 years ago, 33 views

There is an app that has implemented the Android foreground service and stores values as Shared Preferences inside a handler that operates continuously every certain second (which operates in recursive format approximately every 3 seconds). Most of them seem to work well, but all the data stored in Shared Preferences in the app at irregular intervals has been deleted (not only in the service, but also in other activities), and I'm not sure if the handler kept running in the service and the phone exploded. Is there a problem with initializing the value in addition to deleting the data by the user? (Of course, I didn't write the deletion function provided by Shared Preferences.))

public Boolean read() {    
SharedPreferences pref = getApplicationContext().getSharedPreferences("app", Context.MODE_MULTI_PROCESS);
return pref.getBoolean("data", false);
}
public void write(boolean value) {
SharedPreferences pref = getApplicationContext().getSharedPreferences("app", Context.MODE_MULTI_PROCESS);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("data", value);
editor.commit();
}

Within the class in which MultiDex was inherited, only the datatype and the name were different, and they were all saved in that way. I'm really desperate, so please answer me.

More) When I looked at the logs inside the handler, I kept seeing the logs as shown below in a specific cycle.

background concurrent copying gc freed 7060(663kb) allocspace objects ....
I/zygote64: Do partial code cache collection, code=61KB, data=39KB
I/zygote64: After code cache collection, code=61KB, data=39KB
I/zygote64: Increasing code cache capacity to 256KB

I'm going to upload it to see if it's related to this.

android

2022-09-20 20:13

1 Answers

Context, according to Document.It can be seen that the MODE_MULTI_PROCESS constant has been Deferred in API level 23. In fact, reading Shared Preferences in MODE_MULTI_PROCESS mode does not guarantee stability when multiple processes approach it. MODE_MULTI_PROCESS is just to prevent the getSharedPreferences() step from checking if the same sharedPreferences are already being used elsewhere.

Also, if you modify Shared Preferences in several places, it will reset to the initial value. https://stackoverflow.com/questions/31056285/shared-preferences-deleted-automatically https://stackoverflow.com/questions/7438195/sharedpreferences-are-sometimes-deleted

Therefore, I think you should use Content Provider as recommended by Documentation, or create and write a class to manage Shared Preferences.


2022-09-20 20:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.