簡體   English   中英

Android-從WebView保存數據

[英]Android - Save data from WebView

當前,我在應用程序中使用WebView加載網頁。 我已經在WebView加載了以下網頁URL:

http://domain_name/app/

如果未登錄用戶,則URL將重定向到另一個URL,即登錄URL。 這是登錄URL:

http://domain_name/app/index.php?r=site/login

用戶輸入用戶名和密碼后,它將重定向到以下URL:

http://domain_name/app/index.php?r=site/homepage

當用戶成功登錄后,就會向用戶顯示主頁。

我的問題是,當從“最近的列表”中刪除應用程序時,登錄數據將丟失,並且應用程序將重定向到“登錄”屏幕。

我有一種解決此問題的方法。 首先是在用戶成功登錄后最初給Login頁面URL,我將URL更改為Homepage URL,而不是Login page URL。

還有其他方法可以解決此問題,也可以將登錄數據保存到應用程序存儲中嗎?

我在回答自己的問題,我認為這可能對其他人有幫助。

最后,我通過在內部和外部存儲中進行緩存解決了我的問題(如果可用,將數據保存到外部存儲中)

首先,我創建了自定義Application類,該類在內部或外部存儲中創建緩存存儲路徑。

MyApplication.java

import android.app.Application;
import android.os.Environment;

import java.io.File;

public class MyApplication extends Application {

protected File extStorageAppBasePath;
protected File extStorageAppCachePath;

@Override
public void onCreate() {
    super.onCreate();
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        File externalStorageDir = Environment.getExternalStorageDirectory();
        if (externalStorageDir != null) {
            extStorageAppBasePath = new File(externalStorageDir.getAbsolutePath() +
                    File.separator + "Android" + File.separator + "data" +
                    File.separator + getPackageName());
        }

        if (extStorageAppBasePath != null) {
            extStorageAppCachePath = new File(extStorageAppBasePath.getAbsolutePath() +
                    File.separator + "cache");

            boolean isCachePathAvailable = true;

            if (!extStorageAppCachePath.exists()) {
                isCachePathAvailable = extStorageAppCachePath.mkdirs();
            }

            if (!isCachePathAvailable) {
                extStorageAppCachePath = null;
            }
        }
    }
}

@Override
public File getCacheDir() {
    if (extStorageAppCachePath != null) {
        return extStorageAppCachePath;
    }
    else {
        return super.getCacheDir();
    }
}

}

在Android清單文件中,我在application標簽下給出了以下權限和應用程序名稱。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <application
        android:name=".MyApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
........................................
</application>

然后,如果緩存可用,則最終啟用緩存以從存儲中加載。

mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

在加載頁面之前,請使用:

CookieManager.getInstance().setAcceptCookie(true);

如果無法正常工作,請閱讀有關CookieSyncManager的信息,以同步瀏覽器cookie存儲在RAM和永久存儲中。

對於棒棒糖及以上,這應該足夠了:

CookieManager.getInstance().setAcceptThirdPartyCookies(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM