Android Webview加载其他网址

时间:2013-09-09 10:28:44

标签: android webview

我有一个webview,是的,我做的。 :) 无论如何,我加载我的主URL很好,但我需要在某个时候以编程方式加载另一个URL。问题是它在某种程度上打开了另一个webview,我知道这一点,因为当我使用finish()方法退出app时,后一个url的webview关闭,但另一个webview保持打开状态。我该怎么办?我应该打电话销毁webview还是别的什么?

我只是使用webview.loadUrl( url here )方法加载它们。

以下是我的主要活动内容:

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

}

我还应该包括清单吗?提前谢谢。

2 个答案:

答案 0 :(得分:5)

将其放入您的网络活动:

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

然后设置:

your_webview.setWebViewClient(new MyWebViewClient());

希望这会对你有所帮助

答案 1 :(得分:0)

如果没有必要的代码,我必须假设这是您需要添加到实现中的内容。

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