Hybrid Android App中通過js訪問Shared Preferences的問題

來源:互聯網
上載者:User

標籤:android   html5   外掛程式   shared preferences   

      昨天研究Hybrid Android App中js和java代碼之間資料共用的問題,具體情境是使用者登入是android java實現,但有些業務是使用html5開發的,因此登入後到首頁後,調整到某些HTML5業務頁面需要傳遞使用者的access_token,  目前想到的辦法是在js端通過cordova外掛程式訪問存在Shared Preferences中的資料,但由於資料是非同步返回的,需要一定的時間,有時不能及時取得資料,所以問題不能完美的解決。

      目前訪問Shared Preferences的Cordova外掛程式有2個,一個是

 https://github.com/offbye/phonegap-sharedpreferences-save-retrieve, 這個外掛程式只支援Android平台,好處是可以指定Shared Preferences檔案的名字


     另一個是在官方Cordova Plugin上的外掛程式,https://github.com/apla/me.apla.cordova.app-preferences, 優點是支援Android,iOS,WP等多個平台,缺點是在android上,不能指定Shared Preferences檔案的名字,只能訪問預設的Shared Preferences檔案,即通過

 PreferenceManager.getDefaultSharedPreferences(this)建立的檔案,檔案名稱是packagename_preference.xml。

考慮到我這個應用是跨多個平台的,因此最終選擇了me.apla.cordova.app-preferences。

注意代碼需要加在 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");            }}

     由於取得Shared Preferences中的資料是非同步,並且稍微有點慢,因此如果馬上就使用取得的資料,可能會出現問題,目前還沒有徹底解決。一直可行的思路是Android java直接把資料寫入到webview的local Storage資料庫,該資料庫是sqlite的,然後js端通過Localstorage讀取資料,這種方法暫時還沒有驗證可行性。

Hybrid Android App中通過js訪問Shared Preferences的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.