Android studio:在 webview 上暂停和恢复会话

Android studio: pause and resume session on webview

有没有办法在不在本地保存用户名和密码的情况下让用户即使在重启后也能登录?。我只想在应用程序关闭时暂停会话,然后在应用程序打开时恢复。

两种都试过了:

    myWebView.getSettings().setDomStorageEnabled(true);
    myWebView.getSettings().setAppCacheEnabled(true);

还尝试了 CookieManager 并设法做了我想做的事,但由于某种原因,它停止工作并在应用程序退出时不断注销用户(我还是新手,我不知道发生了什么,也无法修复它)。所以我试图找到一种不同的方法来做到这一点。

我的MainActivity.java:

public class MainActivity extends AppCompatActivity {

public DrawerLayout dLayout;
private WebView myWebView;
public ActionBarDrawerToggle actionBarDrawerToggle;

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTitle("Updates");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //CREATE A FOLDER
    File file = this.getBaseContext().getExternalFilesDir("downloads");
    if (!file.exists())
        file.mkdir();
    setNavigationDrawer(); // call method
    dLayout = findViewById(R.id.my_drawer_layout);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, dLayout, R.string.nav_open, R.string.nav_close);

    dLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();

    // to make the Navigation drawer icon always appear on the action bar
    Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
    myWebView = findViewById(R.id.activity_main_webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.getSettings().setDomStorageEnabled(true);
    myWebView.getSettings().setAppCacheEnabled(true);
    myWebView.setWebChromeClient(new WebChromeClient());

    String url = "http://192.168.43.105/public_html/central/updates.php";
    myWebView.loadUrl(url);
    myWebView.setWebViewClient(new WebViewClient());
    myWebView.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
            Toast.makeText(MainActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();

        }

        public void onPageFinished(WebView webView, String url) {
            CookieManager.getInstance().flush();
        }


    });
    myWebView.getSettings().setSupportZoom(true);
    myWebView.getSettings().setBuiltInZoomControls(true);
    myWebView.getSettings().setDisplayZoomControls(false);
    myWebView.getSettings().setUseWideViewPort(false);

}

这是我使用的工作代码。试试这些。

 /*Webview settings.*/

public 静态字符串 DATABASES_SUB_FOLDER = "/databases";

    public void setWebSettings(WebSettings webSettings) {
        this.webSettings = webSettings;
        /*Accept Cookie*/
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setAcceptThirdPartyCookies(webview, true);
        }
        final String filesDir = getFilesDir().getPath();
        final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER;

        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setPluginState(WebSettings.PluginState.OFF);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //   webSettings.setUseWideViewPort(true);
//        webSettings.setUserAgentString("Mozilla/5.0 (Linux; Android 10; SM-G970F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3396.81 Mobile Safari/537.36");
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.supportZoom();
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        webSettings.setGeolocationEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//        webSettings.setSupportMultipleWindows(true);
        webSettings.setSaveFormData(true);
        webSettings.setSavePassword(true);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // chromium, enable hardware acceleration
            webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else {
            // older android version, disable hardware acceleration
            webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }

        /*acces file url*/
        if (Build.VERSION.SDK_INT >= 16) {
            webSettings.setAllowFileAccessFromFileURLs(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
        }

        if (Build.VERSION.SDK_INT < 18) {
            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        }

        if (Build.VERSION.SDK_INT < 19) {
            webSettings.setDatabasePath(databaseDir);
        }

        if (Build.VERSION.SDK_INT >= 21) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true);
        }

    }
    CookieManager.getInstance().setAcceptCookie(true);

    myWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {

            //Do you have cookies?
            Log.d("logged", "url: " + url + ", cookies: " + CookieManager.getInstance().getCookie(url));
        }

    });

    String url = "http://192.168.43.105/public_html/central/updates.php";
    myWebView.loadUrl(url);

终于成功了(同样,我可能不小心删除了一行)。我的网站在用户登录后创建一个名为“logged”的 cookie,其中包含用户的姓名。在 onCreate 添加代码。