目前,我在应用程序中使用 WebView
来加载网页。我已在 WebView
中加载以下网页 URL:
http://domain_name/app/
如果用户未登录,则 URL 将重定向到另一个 URL,即登录 URL。这是登录网址:
http://domain_name/app/index.php?r=site/login
用户输入用户名和密码后,将重定向到以下 URL:
http://domain_name/app/index.php?r=site/homepage
当用户成功登录时,就会向用户显示主页。
我的问题是,当应用程序从“最近”列表中删除时,登录数据会丢失,并且应用程序会重定向到登录屏幕。
我有一种方法可以解决这个问题。首先是在用户成功登录后最初给出登录页面 URL,我将 URL 更改为主页 URL 而不是登录页面 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 Manifest 文件中,我在 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);
关于Android - 从WebView保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32305414/