简体   繁体   English

Android中的WebView加载过时的内​​容

[英]WebView in android loading stale content

I am making an application which uses webview to display content from a url for a logged in user.It's a very basic and small application. 我正在制作一个使用Webview为登录用户显示URL内容的应用程序,这是一个非常基本的小型应用程序。 My problem is that the user logs out and some other user logs in, the previously loaded content(stale content) is displayed. 我的问题是,该用户注销,而其他一些用户登录,则显示先前加载的内容(陈旧的内容)。 Here's the java class: 这是java类:

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class WebViewActivity extends Activity {
    boolean clearHistory;
    private final String API_KEY = "apiKey";
    private final String TOKEN = "token";
    private WebView mWebView;
    String TAG="Response";
    TextView topbar;
    LinearLayout parentLayout;
    HashMap<String, String> maps = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        mWebView =(WebView)findViewById(R.id.webview1);
        mWebView.stopLoading();
        topbar=(TextView)findViewById(R.id.topbar);
        parentLayout=(LinearLayout)findViewById(R.id.parentLayout);

        SharedPreferences pref = getSharedPreferences("MyPref", 0);
        final String webviewUrl = pref.getString("webviewUrl", "");
        final String token = pref.getString("app_token", "");
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);


        topbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(WebViewActivity.this);
                alertDialog.setTitle("Confirm Logout");
                alertDialog.setMessage("Are you sure you want to logout?");
                alertDialog.setIcon(R.drawable.smlalo);
                alertDialog.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {

                        SharedPreferences pref = getSharedPreferences(
                                "MyPref", 0);
                        SharedPreferences.Editor editor = pref.edit();
                        editor.putString("webviewUrl", "");
                        editor.putString("app_token", "");
                        editor.commit();
                        maps.put(TOKEN,token);
                        maps.put(API_KEY, BuildConfig.API_KEY_VALUE);
                        RestClient.getApiInterface().logout(maps).enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                startActivity(new Intent(WebViewActivity.this, MainActivity.class));
                                finish();
                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {

                            }
                        });
                    }
                });

                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                // Showing Alert Message
                alertDialog.show();
            }
        });

        final ProgressDialog progressDialog = ProgressDialog.show(WebViewActivity.this, "", "Loading...");

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onLoadResource(WebView view, String url) {
                view.clearHistory();
                super.onLoadResource(view,url);
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                progressDialog.show();
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "Processing webview url click...");
//                view.loadUrl(url);
                super.shouldOverrideUrlLoading(view, url);
                return false;
            }
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                view.loadUrl(request.getUrl().toString());
                super.shouldOverrideUrlLoading(view, request);
                return false;
            }
            public void onPageCommitVisible(WebView view, String url) {
                view.clearHistory();
                view.clearCache(true);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "Finished loading URL: " +url);
                topbar.setVisibility(View.VISIBLE);
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                /*if (clearHistory)
                {
                    clearHistory = false;
                    mWebView.clearHistory();
                    mWebView.clearCache(true);
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                }*/
                super.onPageFinished(view, url);
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.e(TAG, "Error: " + description);
                new android.app.AlertDialog.Builder(WebViewActivity.this)
                        .setTitle("Error")
                        .setMessage(description)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                super.onReceivedError(view,errorCode,description,failingUrl);
            }
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                new android.app.AlertDialog.Builder(WebViewActivity.this)
                        .setTitle("Error")
                        .setMessage(error.getDescription())
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
                super.onReceivedError(view, request, error);
            }
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view,
                                            WebResourceRequest request, WebResourceResponse errorResponse) {

                Toast.makeText(WebViewActivity.this, "WebView Error" + errorResponse.getReasonPhrase(), Toast.LENGTH_SHORT).show();

                super.onReceivedHttpError(view, request, errorResponse);
            }

        });
        /*mWebView.loadUrl("about:blank");
        mWebView.reload();*/
        mWebView.loadUrl(webviewUrl);
//        clearHistory = true;
//        mWebView.reload();
    }

}

and here's the layout file: 这是布局文件:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:id="@+id/parentLayout"
    android:layout_height="fill_parent"
    tools:context=".SplashActivity">

    <RelativeLayout
        android:background="@color/colorPrimary"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".2"
        android:padding="10dp"
        android:id="@+id/topbarbbb">

    <ImageView
        android:text="@string/coachapp"
        android:layout_width="wrap_content"
        android:layout_centerVertical="true"
        android:src="@drawable/smlalo"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerInParent="true"
        android:id="@+id/imageView2" />
    <TextView
        android:text="Logout"
        android:textSize="12sp"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:visibility="gone"
        style="@style/Base.TextAppearance.AppCompat.Button"
        android:id="@+id/topbar"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerInParent="true">

    </TextView>

</RelativeLayout>

    <WebView android:id="@+id/webview1"
        android:layout_below="@+id/topbarbbb"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />
</LinearLayout>

Also to mention, I have debugged and researched for this. 另外,我已经对此进行调试和研究。 The sharedpreferences are not a problem, the url being retrieved is the one I want to display. sharedpreferences没问题,要检索的URL是我要显示的URL。 It opens properly in the browser. 它会在浏览器中正确打开。 Have tried all the previous answers like Clear previously loaded Webview's content before loading the next one , clear webview history and this one: Destroying the WebView . 尝试了所有先前的答案,例如在加载下一个之前清除先前加载的Webview的内容,清除Webview的 历史记录以及以下内容: 销毁WebView None of these works for me. 这些都不适合我。
I'd really appreciate some help. 我真的很感谢您的帮助。

I figured it out. 我想到了。 Turns out because of using javascript in the webview, it led to creation of cookies. 事实证明,由于在Web视图中使用javascript,导致创建了cookie。 I just had to add the code to clear cookies after successful log out. 成功注销后,我只需要添加代码以清除cookie。 Here's what I used: 这是我使用的:

@SuppressWarnings("deprecation")
public static void clearCookies(Context context)
{

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        Log.d(C.TAG, "Using clearCookies code for API >=" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
        CookieManager.getInstance().removeAllCookies(null);
        CookieManager.getInstance().flush();
    } else
    {
        Log.d(C.TAG, "Using clearCookies code for API <" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
        CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
        cookieSyncMngr.startSync();
        CookieManager cookieManager=CookieManager.getInstance();
        cookieManager.removeAllCookie();
        cookieManager.removeSessionCookie();
        cookieSyncMngr.stopSync();
        cookieSyncMngr.sync();
    }
}

Complete answer can be found here: clear cookies webview 完整的答案可以在这里找到: 清除cookie webview

This issue can occur due to javascript cookies saved on your web view. 由于您的网络视图中保存了javascript cookie,因此可能会发生此问题。 Refresh cookies before opening your webview. 在打开Web视图之前刷新cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM