【发布时间】:2020-02-06 18:55:28
【问题描述】:
我们在 Playstore 中有一个使用 Cordova 开发的应用程序。 现在我们已经在 Native Android 中重建了整个应用程序。
现在我们想将用户从以前的应用升级到新的应用,而无需注销。
为此,如何将 Cordova(window.localStorage) 的本地数据迁移到 Android 共享首选项?
【问题讨论】:
标签: android ios cordova cross-platform
我们在 Playstore 中有一个使用 Cordova 开发的应用程序。 现在我们已经在 Native Android 中重建了整个应用程序。
现在我们想将用户从以前的应用升级到新的应用,而无需注销。
为此,如何将 Cordova(window.localStorage) 的本地数据迁移到 Android 共享首选项?
【问题讨论】:
标签: android ios cordova cross-platform
最后我迁移本地数据如下
- 在 Activity/Fragment 视图中添加 webView 和
final WebView webView = findViewById(R.id.webView);
WebSettings webSetting = webView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient());
//set callback to get data from webview to Native
webView.addJavascriptInterface(new MyJavaScriptInterface(), "MyHandler");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
//Create HTML file to read stored data in webView local storage and pass it to Native
webView.loadUrl("file:///android_asset/readData.html");
- 创建类
MyJavaScriptInterface在webView和native之间进行如下通信
public class MyJavaScriptInterface {
@JavascriptInterface
public void sendKeyValue(String key, String value) {
Log.d("sendKeyValue", "key:" + key + " value:" + value);
}
}
在 assets 文件夹中添加以下 readData.html 文件
<html> <body> <div id="result"></div> <div id="resultCount"></div> <script> // Check browser support if (typeof(Storage) !== "undefined") { for(i = 0; i < localStorage.length; i++) { console.log("key "+i+" "+localStorage.key(i)); console.log("value"+i+" "+localStorage.key(i)+"= "+localStorage.getItem(localStorage.key(i))); window.MyHandler.sendKeyValue(localStorage.key(i), localStorage.getItem(localStorage.key(i))); } } </script> </body> </html>
【讨论】:
使用cordova-plugin-nativestorage。
通过在 Android 中本地实现 SharedPreferences 在 iOS 中实现 NSDefault,它允许在 Android 和 iOS 中保存数据的简单而原生的持久化方法。
JavaScript:
cordova plugin add cordova-plugin-nativestorage
NativeStorage.setItem("username","kalidoss",setSuccess, setError);
function setSuccess(obj) {
alert(obj);
}
function setError(error) {
alert(error.code);
}
Java:
Context context =this;
String MyPREFERENCES = "NativeStorage";
SharedPreferences sharedpreferences = context.getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
String name= sharedpreferences.getString("username","");
【讨论】: