ปัญหาการหมดเวลาของ WebView ขณะเข้าถึงเว็บไซต์ที่ได้รับการรับรองความถูกต้องของ AD

ฉันใช้การตั้งค่าบูลีนการหมดเวลา 20 วินาทีหลังจากนั้นควรเกิดการหมดเวลาและ webview ควรหยุดโหลดหน้าเว็บ นี่คือรหัส:

เว็บ.java

public class Web extends Activity {
private WebView webView;
final Activity activity = this;
public Uri imageUri;
Global ht;
boolean timeout = true;
ProgressDialog progressDialog;
private static final int FILECHOOSER_RESULTCODE = 2888;
private ValueCallback<Uri> mUploadMessage;
@SuppressWarnings("unused")
private Uri mCapturedImageURI = null;
public static final int REQUEST_SELECT_FILE = 100;
public ValueCallback<Uri[]> uploadMessage;
private ProgressBar progressBar;
Handler myHandler = new Handler(Looper.myLooper());
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_PROGRESS);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_web);
    getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    myHandler = new Handler(Looper.myLooper());
    progressBar.setMax(100);
    ht = (Global) getApplicationContext();
    webView = (WebView) findViewById(R.id.webView1);
    webView.setWebViewClient(new MyWebViewClient());

    final String url = "http://192.168.1.1";
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(url);


    //webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    //webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.setFocusable(false);
    webView.setFocusableInTouchMode(false);
    //webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    if (Build.VERSION.SDK_INT >= 19) {

        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    } else {

        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }

    int DELAY = 1000;

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            webView.loadUrl(url);
        }
    }, DELAY);

    /*Timer myTimer = new Timer();
    //Start this timer when you create you task
    myTimer.schedule(loaderTask, 3000); // 3000 is delay in millies*/

    // webView.getSettings().setUseWideViewPort(true);

    // Other webview settings
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(true);
    webView.setVerticalScrollBarEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setPluginState(PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setSupportZoom(true);
    //webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    webView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            // for downloading directly through download manager
            final String filename = URLUtil.guessFileName(url,
                    contentDisposition, mimetype);
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));

            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); //This is important!
            intent.addCategory(Intent.CATEGORY_OPENABLE); //CATEGORY.OPENABLE
            intent.setType("*/*");//any application,any extension
            Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                    Toast.LENGTH_LONG).show();
        }
    });




    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView view, int progress) {
            progressBar.setProgress(progress);
        }



        // The undocumented magic method override
        // Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Web.this.startActivityForResult(
                    Intent.createChooser(i, "File Chooser"),
                    FILECHOOSER_RESULTCODE);

        }

        // For Android 3.0+
        @SuppressWarnings({"unused", "rawtypes", "unchecked"})
        public void openFileChooser(ValueCallback uploadMsg,
                                    String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Web.this.startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FILECHOOSER_RESULTCODE);
        }

        // For Android 4.1
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            Web.this.startActivityForResult(
                    Intent.createChooser(i, "File Chooser"),
                    Web.FILECHOOSER_RESULTCODE);

        }

        // For Android 5.0+
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView mWebView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         WebChromeClient.FileChooserParams fileChooserParams) {
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }

            uploadMessage = filePathCallback;
            Intent intent = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                intent = fileChooserParams.createIntent();
            }
            try {
                startActivityForResult(intent, REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                uploadMessage = null;
                Toast.makeText(getApplicationContext(),
                        "Cannot Open File Chooser", Toast.LENGTH_LONG)
                        .show();
                return false;
            }
            return true;
        }

    });


}

private class MyWebViewClient extends WebViewClient {


    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);

        return true;

    }


    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
        //Your code to do
        try {
            webView.stopLoading();
        } catch (Exception e) {
        }

        if (webView.canGoBack()) {
            webView.goBack();
        }

        webView.loadUrl("about:blank");
        AlertDialog alertDialog = new AlertDialog.Builder(Web.this).create();
        alertDialog.setTitle("Error");
        alertDialog.setMessage("Could not load content Due to bad connectivity or invalid credentials");
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
                startActivity(getIntent());
            }
        });
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            }
        });

        alertDialog.show();
    }

    /*public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
        try {
            webView.stopLoading();
        } catch (Exception e) {
        }

        if (webView.canGoBack()) {
            webView.goBack();
        }

        webView.loadUrl("about:blank");
        AlertDialog alertDialog = new AlertDialog.Builder(Web.this).create();
        alertDialog.setTitle("Error");
        alertDialog.setMessage("Could not load content Due to bad connectivity or invalid credentials");
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
                startActivity(getIntent());
            }
        });
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            }
        });

        alertDialog.show();
        super.onReceivedError(webView, errorCode, description, failingUrl);
    }

    @TargetApi(android.os.Build.VERSION_CODES.M)
    @Override
    public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
        // Redirect to deprecated method, so you can use it in all SDK versions
        onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
    }*/
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setProgress(0);
        Toast.makeText(getApplicationContext(), "Gathering content, please wait", Toast.LENGTH_SHORT).show();

            Runnable run = new Runnable() {
                public void run() {

                    if (timeout) {
                        // do what you want
                        try {
                            webView.stopLoading();
                        } catch (Exception e) {
                        }

                        if (webView.canGoBack()) {
                            webView.goBack();
                        }
                        webView.loadUrl("about:blank");
                        AlertDialog alertDialog = new AlertDialog.Builder(Web.this).create();
                        alertDialog.setTitle("Error");
                        alertDialog.setMessage("Could not load content Due to bad connectivity or invalid credentials");
                        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                                startActivity(getIntent());
                            }
                        });
                        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                Intent i = new Intent(Web.this, LoginActivity2.class);
                                startActivity(i);
                                finish();
                            }
                        });

                        alertDialog.show();
                    }
                }
            };
            myHandler.postDelayed(run, 20000);

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
        progressBar.setProgress(100);
        timeout = false;
    }

    public void onReceivedHttpAuthRequest(WebView view,
                                          HttpAuthHandler handler, String host, String realm) {
        handler.proceed("abc", "123");
        // To change body of overridden  methods  use File| Settings| File Templates.
    }
}



    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    Intent i = new Intent(this, LoginActivity2.class);
                    startActivity(i);
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent intent) {
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        Uri result = intent == null || resultCode != RESULT_OK ? null
                : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }

}
/*class loaderTask extends TimerTask {
    public void run() {

        System.out.println("Times Up");
        if(isPageLoadedComplete){
        }
    }
    }*/}

แต่ทุกครั้งที่ฉันลองใส่ข้อมูลรับรองผิด ค่าบูลีน "หมดเวลา" จะถูกตั้งค่าเป็นเท็จ แทนที่จะให้เป็นจริงในขณะที่เพจเริ่มโหลด ฉันได้ตั้งค่าบูลีนเป็นเท็จเฉพาะเมื่อมีการโหลดหน้าเว็บเสร็จสมบูรณ์แล้ว (ใน onPageFinished()) ของฉัน ในที่สุดหน้าก็ค้างโดยไม่มีผลลัพธ์ ความช่วยเหลือใดๆ เกี่ยวกับวิธีตั้งค่าระยะหมดเวลาหาก webView ไม่สามารถโหลดเนื้อหาจะมีประโยชน์สำหรับฉัน ฉันอ้างอิงลิงก์เหล่านี้แต่ไม่ได้ผล:

ลิงก์1

Link2


person Yogesh Patel    schedule 22.09.2016    source แหล่งที่มา


คำตอบ (1)


ในที่สุดก็ใช้งานได้กับสิ่งนี้:

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

        if(webView.getProgress()==100)
        {
            timeout = false;
        }

    }

อ้างอิงจากลิงก์นี้: Android WebView TimeOut

person Yogesh Patel    schedule 22.09.2016