Yesterday research hybrid Android app in the data sharing between JS and Java code, the specific scenario is that the user login is Android Java implementation, but some of the business was developed using HTML5, so after logging on to the home page, Adjust to some HTML5 business page need to pass the user's Access_token, now think of the method is in the JS side through the Cordova plug-in access to the existing shared preferences data, but because the data is returned asynchronously, it takes a certain amount of time, Sometimes the data cannot be obtained in time, so the problem cannot be solved perfectly.
There are currently 2 Cordova plugins accessing the Shared Preferences , one of which is
Https://github.com/offbye/phonegap-sharedpreferences-save-retrieve, this plugin only supports the Android platform, the advantage is that you can specify Shared Name of the preferences file
Another is on the official Cordova plugin plug-in, Https://github.com/apla/me.apla.cordova.app-preferences, the advantage is to support ANDROID,IOS,WP and other platforms, The disadvantage is that on Android, you cannot specify the name of a shared preferences file, only access the default shared preferences file, which is
Preferencemanager.getdefaultsharedpreferences (This) creates the file with the filename packagename_preference.xml.
Considering that I have this application across multiple platforms, I finally chose me.apla.cordova.app-preferences.
Note that the code needs to be added to the 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 ACCE Ss_token ');} , "Access_token");} }
due to the acquisitionthe data in the Shared preferences is asynchronous and a little bit slow, so if you use the data you get right away, there may be a problem, and it's not completely resolved yet. The idea is that Android Java directly writes data to WebView's local storage database, which is SQLite, and then the JS side reads the data through Localstorage, which is not yet verified to be feasible.
Hybrid access to shared preferences via JS in Android app