【问题标题】:Prevent android webview from loading certain url防止android webview加载某些url
【发布时间】:2012-05-15 19:02:09
【问题描述】:

我想提高我的 webview 的性能。
目前,我的 webview 正在加载我的应用程序不需要的几个资源,例如 *.css 或 *.jpg。

如何防止它加载带有扩展名的 url?

我正在使用 API 级别 7。

【问题讨论】:

  • 从哪里获取 URL?
  • 来自在线游戏。所以我不能操纵网页代码。这个游戏需要大约 100 个 CSS 和图像请求..

标签: android performance webview


【解决方案1】:

如果您只需要页面中的文本,您可以抓取 html 并从那里解析出来:

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    String url = "http://www.google.com";

    BufferedReader reader;
    HttpGet httpGet = new HttpGet(url);
    String result = "";

    try {
        HttpResponse response = httpClient.execute(httpGet, localContext);
        reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = null;
        result = "";
        while ((line = reader.readLine()) != null){
            result += line + "\n";
        }
    } catch(Exception e){}

    // result now contains the html text

或者您甚至可以这样做并重新创建页面,减去 .jpg 和 .css 引用。

【讨论】:

  • 这也是我的第一次尝试。但是由于该站点是一个在线游戏,因此存在大量不同的请求。如果我想这样做,我必须对每个请求的每个参数进行逆向工程。那是大量的工作。另外,我必须做所有其他浏览器的事情,比如存储 cookie 等。
【解决方案2】:

如果您可以接受 API 11 的要求,您可以实现 shouldInterceptRequest 为带有这些扩展名的 URL 返回某种空的 WebResourceResponse

【讨论】:

    【解决方案3】:
    myWebView.setWebViewClient(new MyWebViewClient());
    protected class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
       String ext = MimeTypeMap.getFileExtensionFromUrl(url);
       if (ext.eq.....
    

    【讨论】:

      【解决方案4】:

      防止android webview加载某些url

      你必须检查加载的url是否相等,如果不加载webviw

      MainActivity.Java

      import android.app.AlertDialog;
      import android.app.ProgressDialog;
      import android.content.Context;
      import android.content.Intent;
      import android.graphics.Bitmap;
      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.support.v7.widget.Toolbar;
      import android.util.Log;
      import android.view.MenuItem;
      import android.view.View;
      import android.webkit.WebResourceError;
      import android.webkit.WebResourceRequest;
      import android.webkit.WebView;
      import android.webkit.WebViewClient;
      import android.widget.ImageView;
      public class MainActivity extends AppCompatActivity implements View.OnClickListener {
          private static final String TAG = "WebActivity";
          private Context mContext;
          WebView webview;
          Toolbar toolbar;
          ImageView mBackResource;
          Boolean progress = true;
          private boolean isRedirected = true;
          String urlintent;
          public static ProgressDialog pDialog;
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_webview);
              mContext = MainActivity.this;
              urlintent = "https://www.google.co.in";
              WebView wv = (WebView) findViewById(R.id.webView);
              mBackResource = (ImageView) findViewById(R.id.backarrowwufoo);
              mBackResource.setOnClickListener(this);
              toolbar = (Toolbar) findViewById(R.id.toolbar);
              wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
              wv.loadUrl(urlintent);
              wv.setWebViewClient(new WebViewClient() {
                  @Override
                  public boolean shouldOverrideUrlLoading(WebView view, String url) {
                      Log.e(TAG, "url check" + url + "intent" + urlintent);
                      if (url.equals(urlintent)) {
                          Log.e(TAG, "url check" + url + "intent" + urlintent);
                          //Load your page if it equals
                          view.loadUrl(url);
                          return false; // let me handle this!
                      } else {
                          //Do not load your page if it is not equals
                          return true; // no need to use loadUrl!
                      }
                  }
                  @SuppressWarnings("deprecation")
                  @Override
                  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                      // Handle the error
                      if (errorCode == -2 || errorCode == -8) {
                          view.loadUrl("file:///android_asset/error.html");
                      }
                      if (errorCode == -14) {
                          view.loadData("Page cannot be found on server", "text/html", "UTF-8");
                      }
                  }
                  @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) {
                      // TODO Auto-generated method stub
                      super.onPageStarted(view, url, favicon);
                      //          Log.d("onPageStarted", "onPageStarted:" + url );
                      if (isRedirected) {
                          if (progress) {
                              progress = false;
                              showProgres(mContext);
                          }
                          isRedirected = false;
                      }
                  }
                  @Override
                  public void onLoadResource(WebView view, String url) {
                      super.onLoadResource(view, url);
                      //    Log.v(TAG, "onLoadResource url: " + url);
                  }
                  @Override
                  public void onPageFinished(WebView view, String url) {
                      // TODO Auto-generated method stub
                      super.onPageFinished(view, url);
                      //            Log.d("onPagefinished", "onPagefinished:" + url );
                      if (!isRedirected) {
                          //Do something you want when finished loading
                          isRedirected = true;
                          if (!progress) {
                              hidepDialog();
                              progress = true;
                          }
                      }
                  }
              });
          }
          @Override
          public void onClick(View v) {
              switch (v.getId()) {
                  case R.id.backarrowwufoo:
                      onBackPressed();
                      break;
              }
          }
          @Override
          protected void onDestroy() {
              super.onDestroy();
              if (!progress) {
                  hidepDialog();
                  progress = true;
              }
          }
          public static void showProgres(Context context) {
              pDialog = new ProgressDialog(context);
              pDialog.setMessage("Please wait...");
              pDialog.setCancelable(false);
              showpDialog();
          }
          public static void showpDialog() {
              if (!pDialog.isShowing())
                  pDialog.show();
          }
          public static void hidepDialog() {
              if (pDialog.isShowing())
                  pDialog.dismiss();
          }
      
      }
      

      Activity_main:

      <?xml version="1.0" encoding="utf-8"?>
      <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:id="@+id/main_content"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/white"
          android:fitsSystemWindows="true">
          <android.support.design.widget.AppBarLayout
              android:id="@+id/appbar"
              android:layout_width="match_parent"
              app:elevation="0dp"
              android:layout_height="wrap_content"
              android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
              <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
                  android:id="@+id/toolbar"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:background="@color/colorPrimaryDark"
                  android:minHeight="?attr/actionBarSize">
                  <RelativeLayout
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:paddingRight="10dp">
                      <ImageView
                          android:id="@+id/backarrowwufoo"
                          android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:layout_alignParentLeft="true"
                          android:layout_gravity="center"
                          android:scaleType="center"
                          android:padding="14dp"
                          android:src="@drawable/ic_arrow"
                          android:gravity="center" />
                  </RelativeLayout>
              </android.support.v7.widget.Toolbar>
          </android.support.design.widget.AppBarLayout>
          <WebView
              android:id="@+id/webView"
              android:layout_width="match_parent"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"
              android:padding="10dp"
              android:layout_height="match_parent" />
      </android.support.design.widget.CoordinatorLayout>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 2013-04-18
        相关资源
        最近更新 更多