How to access Shared Preferences through js in Hybrid Android App, hybridandroid
Yesterday I studied the issue of data sharing between js and java code in the Hybrid Android App. The specific scenario is that user login is implemented in android java, but some businesses are developed using html5, therefore, after logging on to the home page, you need to pass your access_token to some HTML5 business pages. The current method is to access data in Shared Preferences through the cordova plug-in on the js end, however, because the data is returned asynchronously, it takes some time and sometimes the data cannot be obtained in time, so the problem cannot be solved perfectly.
Currently, there are two Cordova plug-ins that access Shared Preferences. One is
Https://github.com/offbye/phonegap-sharedpreferences-save-retrieve, which only supports the Android platform, with the benefit of specifying the name of the Shared Preferences File
Another is in the official Cordova plug-in on the plug-in, https://github.com/apla/me.apla.cordova.app-preferences, advantage is support Android, iOS, WP and other platforms, the disadvantage is in android, cannot specify the name of the Shared Preferences file, only the default Shared Preferences file can be accessed.
PreferenceManager. getdefasharsharedpreferences (this) is created in packagename_preference.xml.
Considering that my application is cross-platform, I finally chose me. apla. cordova. app-preferences.
Note that the Code must be added to onDeviceReady,
document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { var appp = window.plugins.appPreferences; if (appp){ appp.fetch (function (access_token) { AppConfig.common.access_token = access_token; localStorage.setItem("access_token", access_token); console.error ('fetch value ok for access_token'); }, function (err) { console.error ('fetch value failed for access_token'); }, "access_token"); }}
Since the data obtained from Shared Preferences is asynchronous and a little slow, if you use the obtained data right away, problems may occur, which has not been completely solved yet. It is always feasible that Android java directly writes data to the local Storage database of webview. The database is sqlite and then the js end reads data through Localstorage. This method is not feasible yet.