WebView不会加载特定的网址

时间:2018-08-07 19:42:59

标签: webview

我无法修复我的应用。我在网上搜索了许多小时,并尝试了许多不同的方法,但不幸的是,我无法自己修复它。问题是我的WebView无法打开特定的URL。这些URL是安全网页上的超链接。多数情况下,URL不起作用,但有时它们不起作用。我不知道为什么经过所有尝试,我的代码有点混乱。这些网址确实可以在普通浏览器中使用。你们知道我在做什么错吗? A screenshot of the URLs

public class MainActivity extends AppCompatActivity {

//Webview variabelen
WebView browser;
// 2x Drukken om af te sluiten
boolean doubleBackToExitPressedOnce = false;
// Camera-/ file explorer toegang
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
public static final int INPUT_FILE_REQUEST_CODE = 1;
// TImer aanraken scherm
private long startTime=15*60*1000;
private final long interval = 1 * 1000;
private MyCountDownTimer countDownTimer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    countDownTimer = new MyCountDownTimer(startTime, interval);

    //Controleer internetverbinding
    if (!isConnected(MainActivity.this)) buildDialog(MainActivity.this).show();
    setContentView(R.layout.activity_main);
    {
        setContentView(R.layout.activity_main);
//                requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
//               

    }
    //Zorgt ervoor dat de browser de app niet verlaat
    browser = (WebView) findViewById(R.id.webView);
    browser.setWebViewClient(new CustomWebViewClient());

    //definieer de link
    String url = "here's antorer url";
    //koppel link aan webview
    WebView view = (WebView) this.findViewById(R.id.webView);
    browser.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 ); // 10MB
    browser.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
    browser.getSettings().setAllowFileAccess( true );
    browser.getSettings().setAppCacheEnabled( true );
    browser.getSettings().setJavaScriptEnabled( true );
    browser.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
    //Dom storage toestaan in webview
    browser.getSettings().setDomStorageEnabled(true);
    //websettings ophalen
    WebSettings webSettings = browser.getSettings();
    //javascript toestaan in websettings
    webSettings.setJavaScriptEnabled(true);
    //Dom storage toestaan in websettings
    webSettings.setDomStorageEnabled(true);
    //database toestaan in websettings
    webSettings.setDatabaseEnabled(true);
    //lettertype grootte aanpassen in websettings
    webSettings.setMinimumFontSize(1);
    webSettings.setMinimumLogicalFontSize(1);
    //database toestaan in webview
    browser.getSettings().setDatabaseEnabled(true);
    //lettertype grootte aanpassen in webview
    browser.getSettings().setMinimumFontSize(1);
    browser.getSettings().setMinimumLogicalFontSize(1);
    //aangepaste webview
    //mogelijkheid tot zoomen uitgezet
    webSettings.setSupportZoom(false);
    //websettings kan lokaal bestanden ophalen
    webSettings.setAllowFileAccess(true);
    webSettings.setAllowContentAccess(true);

    //enable javascript en sta cookies toe
    browser.getSettings().setJavaScriptEnabled(true);
    CookieManager.getInstance().setAcceptCookie(true);

    //laad link
    browser.loadUrl(url);

    //browser krijgt toegang tot file explorer
    browser.setWebChromeClient(new WebChromeClient() {
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                }
                if (photoFile != null) {
                    mCameraPhotoPath = "file: " + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
                if (photoFile != null) {
                    mCameraPhotoPath = "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("image/*");

            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);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    setTheme(R.style.STYLE);
    if (item.getItemId() == R.id.action_actie) {
        browser.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("android_asset") ){
                    // Can be clever about it like so where myshost is defined in your strings file
                    // if (Uri.parse(url).getHost().equals(getString(R.string.myhost)))
                    browser.loadUrl(url);
                    return false;
                }
                // open rest of URLS in default browser
                browser.loadUrl(url);
                return true;
            }
        });
        String url_thing = "here's my url";
        WebView browser= (WebView) this.findViewById(R.id.webView);
        browser.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 ); // 10MB
        browser.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
        browser.getSettings().setAllowFileAccess( true );
        browser.getSettings().setAppCacheEnabled( true );
        browser.getSettings().setJavaScriptEnabled( true );
        browser.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
        browser.setWebViewClient(new WebViewClient());
        //Dom storage toestaan in webview
        browser.getSettings().setDomStorageEnabled(true);
        //websettings ophalen
        WebSettings webSettings = browser.getSettings();
        //javascript toestaan in websettings
        webSettings.setJavaScriptEnabled(true);
        //Dom storage toestaan in websettings
        webSettings.setDomStorageEnabled(true);
        //database toestaan in websettings
        webSettings.setDatabaseEnabled(true);
        //lettertype grootte aanpassen in websettings
        webSettings.setMinimumFontSize(1);
        webSettings.setMinimumLogicalFontSize(1);
        //database toestaan in webview
        browser.getSettings().setDatabaseEnabled(true);
        //lettertype grootte aanpassen in webview
        browser.getSettings().setMinimumFontSize(1);
        browser.getSettings().setMinimumLogicalFontSize(1);
        //aangepaste webview
        //mogelijkheid tot zoomen uitgezet
        webSettings.setSupportZoom(false);
        //websettings kan lokaal bestanden ophalen
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        //enable javascript en sta cookies toe
        browser.getSettings().setJavaScriptEnabled(true);
        CookieManager.getInstance().setAcceptCookie(true);
        browser.loadUrl(url_thing);
    }
    if (item.getItemId() == R.id.action_thing1) {
        setTheme(R.style.AppTheme);
        browser.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("android_asset") ){
                    // Can be clever about it like so where myshost is defined in your strings file
                    // if (Uri.parse(url).getHost().equals(getString(R.string.myhost)))
                    browser.loadUrl(url);
                    return false;
                }
                // open rest of URLS in default browser
                browser.loadUrl(url);
                return true;
            }
        });
        String url_thing1 = "here's another url";
        WebView view = (WebView) this.findViewById(R.id.webView);
        browser.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 ); // 10MB
        browser.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
        browser.getSettings().setAllowFileAccess( true );
        browser.getSettings().setAppCacheEnabled( true );
        browser.getSettings().setJavaScriptEnabled( true );
        browser.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
        //Dom storage toestaan in webview
        browser.getSettings().setDomStorageEnabled(true);
        //websettings ophalen
        WebSettings webSettings = browser.getSettings();
        //javascript toestaan in websettings
        webSettings.setJavaScriptEnabled(true);
        //Dom storage toestaan in websettings
        webSettings.setDomStorageEnabled(true);
        //database toestaan in websettings
        webSettings.setDatabaseEnabled(true);
        //lettertype grootte aanpassen in websettings
        webSettings.setMinimumFontSize(1);
        webSettings.setMinimumLogicalFontSize(1);
        //database toestaan in webview
        browser.getSettings().setDatabaseEnabled(true);
        //lettertype grootte aanpassen in webview
        browser.getSettings().setMinimumFontSize(1);
        browser.getSettings().setMinimumLogicalFontSize(1);
        //aangepaste webview
        //mogelijkheid tot zoomen uitgezet
        webSettings.setSupportZoom(false);
        //websettings kan lokaal bestanden ophalen
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        //enable javascript en sta cookies toe
        browser.getSettings().setJavaScriptEnabled(true);
        CookieManager.getInstance().setAcceptCookie(true);
        browser.loadUrl(url_thing1);
    }

        return super.onOptionsItemSelected(item);

}


//app kan fotos maken
private File createImageFile() throws IOException {
    // geeft de foto een naam
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
    return imageFile;
}

//controleer resultaat
@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
    if(requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
        super.onActivityResult(requestCode, resultCode, data);
        return;
    }

    Uri[] results = null;

    //Check of de response goed is
    if(resultCode == Activity.RESULT_OK) {
        if(data == null) {
            // If there is not data, then we may have taken a photo
            if(mCameraPhotoPath != null) {
                results = new Uri[]{Uri.parse(mCameraPhotoPath)};
            }
        } else {
            String dataString = data.getDataString();
            if (dataString != null) {
                results = new Uri[]{Uri.parse(dataString)};
            }
        }
    }
    mFilePathCallback.onReceiveValue(results);
    mFilePathCallback = null;
    return;
}

// wis de app-data (uitloggen)
private void deleteAppData() {
    try {
        String packageName = getApplicationContext().getPackageName();
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("pm clear "+packageName);

    } catch (Exception e) {
        e.printStackTrace();
    } }

// delete app data bij sluiten van de app
@Override
protected void onDestroy() {
    super.onDestroy();
    deleteAppData();
}

// reset tumer bij interactie scherm
@Override
public void onUserInteraction(){
    super.onUserInteraction();
    countDownTimer.cancel();
    countDownTimer.start();
}

// reset timer bij sluiten van de app
public class MyCountDownTimer extends CountDownTimer {
    public MyCountDownTimer(long startTime, long interval) {
        super(startTime, interval);
    }

    @Override
    public void onFinish() {
        deleteAppData();
        onDestroy();
    }
    @Override
    public void onTick(long millisUntilFinished) {
    }
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

//Accapteer cookies van derden
public void setAcceptThirdPartyCookies(boolean accept) {
    CookieManager cookieManager = CookieManager.getInstance();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (browser != null)
            cookieManager.setAcceptThirdPartyCookies(browser, accept);
    } else {
        cookieManager.setAcceptCookie(accept);
    }
}

//terugknop navigeert logisch door de app en laat toast zien voor afsluiten
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    this.doubleBackToExitPressedOnce = true;
    if (browser.canGoBack()){
        browser.goBack();
    } else {
        Toast.makeText(this, "Druk nogmaals op de terugknop om de app af te sluiten", Toast.LENGTH_SHORT).show();}
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);
}

//controleer imternetverbinding
public boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netinfo = cm.getActiveNetworkInfo();
    if (netinfo != null && netinfo.isConnectedOrConnecting()) {
        NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
        else return false;
    } else
        return false;
}

//melding bij geen internetverbinding
public AlertDialog.Builder buildDialog(Context c) {
    AlertDialog.Builder builder = new AlertDialog.Builder(c);
    builder.setTitle("Geen internetverbinding");
    builder.setMessage("Verbind met het internet om de app te gebruiken");
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });
    return builder;
}
private class CustomWebViewClient extends WebViewClient{


    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.contains("android_asset") ){
            browser.getSettings().setJavaScriptEnabled(true);
            browser.getSettings().setDomStorageEnabled(true);
            browser.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 ); // 10MB
            browser.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
            browser.getSettings().setAllowFileAccess( true );
            browser.getSettings().setAppCacheEnabled( true );
            browser.getSettings().setJavaScriptEnabled( true );
            browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            browser.loadUrl("file:///android_asset/connect.php.html");
            browser.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
            //enable javascript en sta cookies toe
            browser.getSettings().setJavaScriptEnabled(true);
            CookieManager.getInstance().setAcceptCookie(true);
            //laad link
            browser.loadUrl(url);

            return false;
        }
        browser.getSettings().setJavaScriptEnabled(true);
        browser.getSettings().setDomStorageEnabled(true);
        browser.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 ); // 10MB
        browser.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
        browser.getSettings().setAllowFileAccess( true );
        browser.getSettings().setAppCacheEnabled( true );
        browser.getSettings().setJavaScriptEnabled( true );
        browser.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
        //enable javascript en sta cookies toe
        browser.getSettings().setJavaScriptEnabled(true);
        CookieManager.getInstance().setAcceptCookie(true);
        //laad link
        browser.loadUrl(url);

        return true;
    }
}


}

0 个答案:

没有答案