Android的web视图加载其他网址 [英] Android Webview loading other URLs

查看:203
本文介绍了Android的web视图加载其他网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个web视图,是我做的。 :)
无论如何,我打开我的主要网址很好,但我需要在某些时候编程方式加载另一个URL。问题是,它有点打开另一个网页流量,我知道这是因为,当我退出使用的应用程序完成()方法,后者网址web视图关闭,但其他的WebView保持打开状态。我该怎么办?我应该叫破坏的WebView还是其他什么东西?

I have a webview, yes i do. :) Anyway, I load my main URL fine, but i need to load another url programmatically at some point. The problem is that it somewhat opens another webview, and I know this because when I exit the app using finish() method, the webview with the latter url closes, but another webview stays open. What should I do? Should i call destroy webview or something else?

我只是加载它们使用的URL webview.loadUrl( URL这里的)方法。

I just load them URLs using webview.loadUrl(url here) method.

下面就是我的主要活动里:

Here's what's inside my main activity:

package com.sample;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity
{

        private WebView wv;
        private ProgressBar progress;
        private static String mycaturl="*url 1*";
        private static String helpurl="*url 2*";
        private static String fbackurl="*url 3*";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
        StrictMode.setThreadPolicy(policy);
        if (reachable(this))
        {
            Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
            buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT, mycaturl );
        }
        else
        {
            Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
            eolc( savedInstanceState );
        }
    }


    @SuppressLint({ "SetJavaScriptEnabled" })
    public void buildwv(Bundle sis, int load, String url)
    {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

        setContentView(R.layout.activity_main);

        //assigning objects to variables
        wv=(WebView) findViewById(R.id.wv);
        wv.setWebViewClient( new wvc() );
        progress=(ProgressBar) findViewById(R.id.progress);

        //websettings
        WebSettings ws = wv.getSettings();
        ws.setAppCacheMaxSize( 100 * 1024 * 1024 ); // 100MB
        ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
        ws.setAllowFileAccess( true );
        ws.setAppCacheEnabled( true );
        ws.setJavaScriptEnabled( true );
        ws.setCacheMode(load);

        //if instance is saved, to catch orientation change
        if(sis==null)
        {   wv.loadUrl(url);    }
    }


    public void eolc(final Bundle sis)
    {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

        AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );

        alertDialog.setTitle("Unreachable Host");
        alertDialog.setMessage("Host is unreachable. Load from cache or exit.");
        alertDialog.setIcon(R.drawable.tick);
        //alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.setCancelable(false);

        alertDialog.setPositiveButton( "Load from Cache", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog,int which)
            {
                // Write your code here to execute after dialog
                Toast.makeText(getApplicationContext(), "You chose to load cache.", Toast.LENGTH_SHORT).show();
                buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, mycaturl );
            }
        });

        alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "You chose Help. EOLC", Toast.LENGTH_SHORT).show();

                buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
            }
        });

        alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                // Write your code here to execute after dialog
                Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        alertDialog.create();
        alertDialog.show();
    }


    public void roe()
    {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

        AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );

        alertDialog.setTitle("Connection Lost");
        alertDialog.setMessage("Connection to host was lost. Restart and load cache or exit.");
        alertDialog.setIcon(R.drawable.tick);
        alertDialog.setCancelable(false);

        alertDialog.setPositiveButton( "Restart", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog,int which)
            {
                Toast.makeText(getApplicationContext(), "You chose to restart and load cache.", Toast.LENGTH_SHORT).show();
                Intent i = getBaseContext().getPackageManager()
                         .getLaunchIntentForPackage( getBaseContext().getPackageName() );
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
                startActivity(i);
            }
        });

        alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "You chose Help. ROE", Toast.LENGTH_SHORT).show();
                wv.stopLoading();
                wv.loadUrl( helpurl );
            }
        });

        alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which)
            {
                Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        alertDialog.create();
        alertDialog.show();
    }


    private class wvc extends WebViewClient
    {
          public void onPageStarted(WebView view, String url, Bitmap favicon)
          {
              progress.setVisibility(View.VISIBLE);

              if (url.contains(mycaturl))
              {
                  WebSettings ws = wv.getSettings();

                  if ( !reachable(getApplicationContext()) )
                  {
                      if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
                      {
                          roe();
                      }
                      else if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
                      {
                          Toast.makeText(getApplicationContext(), "loading cache coz not reachable", Toast.LENGTH_SHORT).show();
                      }
                  }
                  else
                  {
                      if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
                      {
                          Toast.makeText(getApplicationContext(), "Connection to server established.", Toast.LENGTH_SHORT).show();
                      }
                  }
              }
          }

          @Override
          public void onPageFinished(WebView view, String url) 
          {
              super.onPageFinished(view, url);
              Toast.makeText(getApplicationContext(), "PAGE DONE LOADING!!", Toast.LENGTH_SHORT).show();

              //circular progress bar close
              progress.setVisibility(View.GONE);
          }

          @Override
          public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
          {
              super.onReceivedError(view, errorCode, description, failingUrl);
              wv.stopLoading();
              WebSettings ws = wv.getSettings();

              if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
              {
                  wv.loadUrl(helpurl);
                  Toast.makeText(getApplicationContext(), "Page unavailable", Toast.LENGTH_SHORT).show();
              }
              else
              {
                  wv.loadUrl(helpurl);
                  Toast.makeText(getApplicationContext(), "Page not cached", Toast.LENGTH_SHORT).show();
              }
              roe();
          }
      }


    //checking connectivity by checking if site is reachable
    public static boolean reachable(Context context) 
    {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnected()) 
        {
            try 
            {
                URL url = new URL(mycaturl);
                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout(5000); // five seconds timeout in milliseconds
                urlc.connect();
                if (urlc.getResponseCode() == 200) // good response
                {   return true;    } else {    return false;   }
            }
            catch (IOException e)
            {   return false;   }
        }
        else
        {   return false;   }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void onBackPressed ()
    {
        if (wv.isFocused() && wv.canGoBack())
        {   wv.goBack();    }   else {  finish();   }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.item1:
                wv.loadUrl( helpurl );
                break;
            case R.id.item2:
                wv.loadUrl( fbackurl );
                break;
            case R.id.item3:
                String currurl=wv.getUrl();
                wv.loadUrl(currurl);   
                break;
            case R.id.item4:
                Intent i = getBaseContext().getPackageManager()
                 .getLaunchIntentForPackage( getBaseContext().getPackageName() );
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                break;
            case R.id.item5:
                finish();
                break;
            default:
                break;
        }
        return true;
    } 

    @Override
    protected void onSaveInstanceState(Bundle outState )
    {
        super.onSaveInstanceState(outState);
        wv.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onSaveInstanceState(savedInstanceState);
        wv.restoreState(savedInstanceState);
    }

}

我应该还包括清单?先谢谢了。

Should I also include manifest? Thanks in advance.

推荐答案

将这个:

private class MyWebViewClient extends WebViewClient {
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
    view.loadUrl(url);
    return true;
  }
}

然后设置:

your_webview.setWebViewClient(new MyWebViewClient());

希望这会帮助你。

Hope this will help you

这篇关于Android的web视图加载其他网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆