防止android webview加载某些url

时间:2012-05-15 19:02:09

标签: android performance webview

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

如何阻止它加载带扩展名的网址?

我正在使用API​​ Level 7。

4 个答案:

答案 0 :(得分: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引用。

答案 1 :(得分:0)

如果您可以使用API​​ 11,则可以实施shouldInterceptRequest为具有这些扩展名的网址返回某种空WebResourceResponse

答案 2 :(得分:0)

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.....

答案 3 :(得分:0)

防止Android webview加载某些网址

你必须检查加载网址是否等于,如果不加载网页

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>