1

基本的な質問、私は何をしましたか? ハハハ。webview内にURLをロードするために何をしましたか? 最初に shouldOverrideUrlLoading をオーバーライドして、リンクが読み込まれる場所を制御し、一度削除しましたが、URL は webview 内で読み込まれます。そして今、デフォルトのブラウザでリンクを開く必要があるため、URL の読み込みをもう一度オーバーライドする必要がありますが、方法がわかりません。デフォルトのブラウザでURLの読み込みを強制するように他の人が提案したことも試しましたが、うまくいきません。私を助けてください。これが私のコードです:

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

}

マニフェストを含める必要がありますか? 前もって感謝します。

4

1 に答える 1