首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >安卓WebView APP + Laravel“页面已因不活动而过期”

安卓WebView APP + Laravel“页面已因不活动而过期”
EN

Stack Overflow用户
提问于 2019-03-19 14:52:57
回答 1查看 1.5K关注 0票数 0

我刚刚为我的平台创建了一个简单的安卓应用程序(WebView)。在桌面和移动设备上的任何浏览器上都工作得很好,但我在android应用程序上有一个问题。

我有这些情况:

  1. 打开应用程序-登录到仪表板-注销(几秒钟或几分钟后)-重定向到登录页面(这是正常的)
  2. 打开应用程序-登录到仪表板-关闭应用程序-一段时间(30分钟或更长时间)后再次打开应用程序-无需再次登录,我将被重定向至仪表板-我正在尝试注销,然后被重定向至仪表板-我正在尝试再次注销,结果显示此消息:“页面已因不活动而过期”。

注销代码:

<li class="dropdown dropdown-notification nav-item">
              <a class="nav-link nav-link-label" value="{{ csrf_token() }}" href="{{ url('/logout') }}" method="GET" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"><font color="red"><i class="ficon ft-log-out"></i></font></a>
            </li>
            
             <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
                                        {{ csrf_field() }}
                                    </form>

MainActivity.java代码:

package com.siteronics.domainame;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.webkit.ClientCertRequest;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.RenderProcessGoneDetail;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.ProgressDialog;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.webkit.ConsoleMessage;
import android.widget.Toast;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class MainActivity extends AppCompatActivity {
    WebView webView;
    private static final String TAG = MainActivity.class.getSimpleName();
    private String mCM;
    private ValueCallback mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR=1;
    SweetAlertDialog sweetAlertDialog;
    //select whether you want to upload multiple files
    private boolean multiple_files = false;
    String URL="https://domainame.com/login";
//    private AdView mAdView;
//    AdRequest adRequest;
    LinearLayout linearLayout;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        if(Build.VERSION.SDK_INT >= 21){
            Uri[] results = null;
            //Check if response is positive
            if(resultCode== Activity.RESULT_OK){
                if(requestCode == FCR){
                    if(null == mUMA){
                        return;
                    }
                    if(intent == null || intent.getData() == null){
                        //Capture Photo if no image available
                        if(mCM != null){
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    }else{
                        String dataString = intent.getDataString();
                        if(dataString != null){
                            results = new Uri[]{Uri.parse(dataString)};
                        } else {
                            if(multiple_files) {
                                if (intent.getClipData() != null) {
                                    final int numSelectedFiles = intent.getClipData().getItemCount();
                                    results = new Uri[numSelectedFiles];
                                    for (int i = 0; i < numSelectedFiles; i++) {
                                        results[i] = intent.getClipData().getItemAt(i).getUri();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            mUMA.onReceiveValue(results);
            mUMA = null;
        }else{
            if(requestCode == FCR){
                if(null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUM.onReceiveValue(result);
                mUM = null;
            }
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        if(getResources().getBoolean(R.bool.portrait_only)){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        else{
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        Log.e("tag","onCreate");

        setContentView(R.layout.activity_main);

        // Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
//        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
//        MobileAds.initialize(this, "ca-app-pub-8239779269277913~8610652498");
        sweetAlertDialog=new SweetAlertDialog(this,SweetAlertDialog.ERROR_TYPE);

        linearLayout=findViewById(R.id.ll_splash);

//        mAdView = findViewById(R.id.adView);


        final TranslateAnimation animate = new TranslateAnimation(0,-linearLayout.getWidth(),0,0);
        animate.setDuration(500);
        animate.setFillAfter(true);



        webView = (WebView) findViewById(R.id.a);
        assert webView != null;

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        //improve webView performance
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.getSettings().setAppCacheEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);
        webSettings.setEnableSmoothTransition(true);

//        webSettings.setDomStorageEnabled(true);
        if(Build.VERSION.SDK_INT >= 21){
            webSettings.setMixedContentMode(0);
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else if(Build.VERSION.SDK_INT >= 19){
            webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }else {
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        webView.setWebChromeClient(new WebChromeClient());

        CookieSyncManager.createInstance(MainActivity.this);
        CookieSyncManager.getInstance().startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }

        webView.loadUrl(URL);



        webView.setWebChromeClient(new WebChromeClient(){


            //For Android 5.0+
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams){
                if(mUMA != null){
                    mUMA.onReceiveValue(null);
                }
                mUMA = filePathCallback;
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
                    File photoFile = null;
                    try{
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCM);
                    }catch(IOException ex){
                        Log.e(TAG, "Image file creation failed", ex);
                    }
                    if(photoFile != null){
                        mCM = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    }else{
                        takePictureIntent = null;
                    }
                }
                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("*/*");
                if(multiple_files) {
                    contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
//                    contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                }
                Intent[] intentArray;
                if(takePictureIntent != null){
                    intentArray = new Intent[]{takePictureIntent};
                }else{
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                if(multiple_files && Build.VERSION.SDK_INT >= 18) {
                    chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                }
                startActivityForResult(chooserIntent, FCR);
                return true;
            }
        });

        webView.setWebViewClient(new WebViewClient(){



            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                if (!isNetworkConnected()) {

                    new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("Error...")
                            .setContentText("No internet connection!")
                            .setConfirmText("Retry")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    sDialog.dismissWithAnimation();
                                    webView.reload();

                                }
                            })
                            .show();
                    webView.stopLoading();

                    return;
                }


                Log.e("tag","onPageStarted");

                sweetAlertDialog =new SweetAlertDialog(MainActivity.this,SweetAlertDialog.PROGRESS_TYPE);

                sweetAlertDialog.setCancelable(false);

                sweetAlertDialog.setTitle("Loading....");


                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                else
                if (linearLayout.getVisibility()==View.GONE)
                    sweetAlertDialog.show();

                Log.e("tag","onPageStarted");

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //linearLayout.startAnimation(animate);
                Log.e("tag","onPageFinished");
                linearLayout.setVisibility(View.GONE);
//                adRequest = new AdRequest.Builder().build();
//                mAdView.loadAd(adRequest);
//                mAdView.setVisibility(View.VISIBLE);
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
            }



            @Override
            public void onLoadResource(WebView view, String url) {
//                if (sweetAlertDialog.isShowing()){
//                    sweetAlertDialog.dismiss();
//                }

                super.onLoadResource(view, url);
                Log.e("tag","onLoadResource");

            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                super.onReceivedHttpError(view, request, errorResponse);
                Log.e("tag","onReceivedHttpError");

            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
//                if (sweetAlertDialog.isShowing()){
//                    sweetAlertDialog.dismiss();
//                }
                super.doUpdateVisitedHistory(view, url, isReload);
                Log.e("tag","doUpdateVisitedHistory");

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                super.onReceivedSslError(view, handler, error);
                Log.e("tag","onReceivedSslError");

            }

            @Override
            public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                super.onReceivedClientCertRequest(view, request);
                Log.e("tag","onReceivedClientCertRequest");

            }

            @Override
            public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                super.onReceivedHttpAuthRequest(view, handler, host, realm);
                Log.e("tag","onReceivedHttpAuthRequest");

            }

            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                Log.e("tag","shouldOverrideKeyEvent");

                return super.shouldOverrideKeyEvent(view, event);

            }

            @Override
            public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                super.onUnhandledKeyEvent(view, event);
                Log.e("tag","onUnhandledKeyEvent");

            }

            @Override
            public void onScaleChanged(WebView view, float oldScale, float newScale) {
                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                super.onScaleChanged(view, oldScale, newScale);
                Log.e("tag","onScaleChanged");

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);

                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }

                new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Error...")
                        .setContentText("No internet connection!")
                        .setConfirmText("Retry")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.dismissWithAnimation();
                                webView.reload();

                            }
                        })
                        .show();
                Log.e("tag","onReceivedError");

            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);

                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                Log.e("tag","onPageCommitVisible");

            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }

                Log.e("tag","onReceivedError");

            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);

                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                Log.e("tag","onFormResubmission");

            }

            @Override
            public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
                super.onReceivedLoginRequest(view, realm, account, args);

                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                Log.e("tag","onReceivedLoginRequest");

            }

            @Override
            public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
                Log.e("tag","onRenderProcessGone");

                return super.onRenderProcessGone(view, detail);

//                if (sweetAlertDialog.isShowing()){
//                    sweetAlertDialog.dismiss();
//                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.e("tag","shouldOverrideUrlLoading");

                if (sweetAlertDialog.isShowing()){
                    sweetAlertDialog.dismiss();
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    view.loadUrl(request.getUrl().toString());
                }
                return super.shouldOverrideUrlLoading(view, request);
            }


        });

    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
        Log.e("tag","onKeyDown");

        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode){
                case KeyEvent.KEYCODE_BACK:
                    if(webView.canGoBack()){
                        webView.goBack();
                    }else{
                        finish();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }
    private boolean isNetworkConnected() {
        Log.e("tag","isNetworkConnected");

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        return cm.getActiveNetworkInfo() != null;
    }

    @Override
    protected void onRestart() {
        Log.e("tag","onRestart");

        super.onRestart();
        if (sweetAlertDialog.isShowing()){
            sweetAlertDialog.dismiss();
        }
    }

    @Override
    protected void onPostResume() {
        Log.e("tag","onPostResume");

        super.onPostResume();
        if (sweetAlertDialog.isShowing()){
            sweetAlertDialog.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        Log.e("tag","onBackPressed");

        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        Log.e("tag","onDestroy");

        super.onDestroy();
        webView=null;
    }



    // Create an image file
    private File createImageFile() throws IOException{
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_"+timeStamp+"_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg",storageDir);
    }
}

在/resources/views/error上,我试图用html元重定向修改419.blade.php,但问题没有解决。

我想让我的客户长时间登录到仪表板,但也为他们提供了在需要时注销而不会出现任何问题的可能性。

EN

回答 1

Stack Overflow用户

发布于 2019-06-11 03:16:41

您应该删除此行:

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

并使用:

webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55235164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档