Example usage for android.webkit WebView destroy

List of usage examples for android.webkit WebView destroy

Introduction

In this page you can find the example usage for android.webkit WebView destroy.

Prototype

public void destroy() 

Source Link

Document

Destroys the internal state of this WebView.

Usage

From source file:Main.java

public static void releaseWebView(WebView webview) {
    webview.stopLoading();//from w  w  w  .j  a v  a2s . co  m
    webview.setWebChromeClient(null);
    webview.setWebViewClient(null);
    webview.destroy();
    webview = null;
}

From source file:meizhi.meizhi.malin.utils.DestroyCleanUtil.java

@SuppressLint("ObsoleteSdkInt")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void unBindView(View view) {
    if (view == null)
        return;/*from   w  ww .  j  a va2  s  .  c om*/
    Drawable drawable;
    int i;
    //1.
    try {
        view.setOnClickListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //2.
    try {
        view.setOnCreateContextMenuListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //3.
    try {
        view.setOnFocusChangeListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //4.
    try {
        view.setOnKeyListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //5.
    try {
        view.setOnLongClickListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //6.
    try {
        view.setOnTouchListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //7.
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            view.setOnApplyWindowInsetsListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //8.
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            view.setOnContextClickListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //9.
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            view.setOnScrollChangeListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //10.
    try {
        view.setOnDragListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //11.
    try {
        view.setOnGenericMotionListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //12.
    try {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2) {//13
            view.setOnHoverListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //13.
    try {
        view.setOnSystemUiVisibilityChangeListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    /**
     * @see SwipeRefreshLayout#onDetachedFromWindow()
     */
    if (view.getBackground() != null && !view.getClass().getName().equals(CIRCLE_CLASS)) {
        try {
            view.getBackground().setCallback(null);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {//16
                view.setBackgroundDrawable(null);
            } else {
                view.setBackground(null);
            }
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //ImageView
    if (view instanceof ImageView) {
        try {
            ImageView imageView = (ImageView) view;
            drawable = imageView.getDrawable();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            imageView.setImageDrawable(null);
            imageView.setImageBitmap(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //TextView
    if (view instanceof TextView) {
        try {
            TextView textView = (TextView) view;
            textView.setCompoundDrawables(null, null, null, null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                textView.setCompoundDrawablesRelative(null, null, null, null);
            }
            textView.setCursorVisible(false);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //ImageButton
    if (view instanceof ImageButton) {
        try {
            ImageButton imageButton = (ImageButton) view;
            drawable = imageButton.getDrawable();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            imageButton.setImageDrawable(null);
            imageButton.setImageBitmap(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //ListView
    if (view instanceof ListView) {
        ListView listView = (ListView) view;

        try {
            listView.setAdapter(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnScrollListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnItemClickListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnItemLongClickListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnItemSelectedListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //RecyclerView
    if (view instanceof RecyclerView) {
        try {
            RecyclerView recyclerView = (RecyclerView) view;
            recyclerView.setAdapter(null);
            recyclerView.setChildDrawingOrderCallback(null);
            recyclerView.setOnScrollListener(null);
            recyclerView.addOnScrollListener(null);
            recyclerView.removeOnScrollListener(null);
            recyclerView.setRecyclerListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //WebView
    if (view instanceof WebView) {

        WebView webView = (WebView) view;
        try {
            webView.stopLoading();
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.removeAllViews();
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.setWebChromeClient(null);
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.setWebViewClient(null);
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.destroy();
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            if (null != view.getParent() && view.getParent() instanceof ViewGroup) {
                ((ViewGroup) view.getParent()).removeView(view);
            }
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

    }

    //SurfaceView
    if (view instanceof SurfaceView) {
        try {
            SurfaceView surfaceView = (SurfaceView) view;
            SurfaceHolder holder = surfaceView.getHolder();
            if (holder != null) {
                Surface surface = holder.getSurface();
                if (surface != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        surface.release();
                    }
                }
            }
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }
    }

    view.destroyDrawingCache();
    view.clearAnimation();

    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        int childCount = (viewGroup).getChildCount();
        for (i = 0; i < childCount; i++) {
            unBindView((viewGroup).getChildAt(i));
        }
    }
}

From source file:com.just.agentweb.AgentWebUtils.java

static final void clearWebView(WebView m) {

    if (m == null) {
        return;/*from   w w w .  j a  v  a 2s.  c o m*/
    }
    if (Looper.myLooper() != Looper.getMainLooper()) {
        return;
    }
    m.loadUrl("about:blank");
    m.stopLoading();
    if (m.getHandler() != null) {
        m.getHandler().removeCallbacksAndMessages(null);
    }
    m.removeAllViews();
    ViewGroup mViewGroup = null;
    if ((mViewGroup = ((ViewGroup) m.getParent())) != null) {
        mViewGroup.removeView(m);
    }
    m.setWebChromeClient(null);
    m.setWebViewClient(null);
    m.setTag(null);
    m.clearHistory();
    m.destroy();
    m = null;

}

From source file:com.gsma.mobileconnect.helpers.AuthorizationService.java

/**
 * Handles the process between the MNO and the end user for the end user to
 * sign in/ authorize the application. The application hands over to the
 * browser during the authorization step. On completion the MNO redirects to
 * the application sending the completion information as URL parameters.
 *
 * @param config           the mobile config
 * @param authUri          the URI to the MNO's authorization page
 * @param scopes           which is an application specified string value.
 * @param redirectUri      which is the return point after the user has
 *                         authenticated/consented.
 * @param state            which is application specified.
 * @param nonce            which is application specified.
 * @param maxAge           which is an integer value.
 * @param acrValues        which is an application specified.
 * @param context          The Android context
 * @param listener         The listener used to alert the activity to the change
 * @param response         The information captured in the discovery phase.
 * @param hmapExtraOptions A HashMap containing additional authorization options
 * @throws UnsupportedEncodingException/*from ww w  . j  av a 2  s  . c o  m*/
 */
public void authorize(final MobileConnectConfig config, String authUri, final String scopes,
        final String redirectUri, final String state, final String nonce, final int maxAge,
        final String acrValues, final Context context, final AuthorizationListener listener,
        final DiscoveryResponse response, final HashMap<String, Object> hmapExtraOptions)
        throws UnsupportedEncodingException {
    final JsonNode discoveryResponseWrapper = response.getResponseData();
    final JsonNode discoveryResponseJsonNode = discoveryResponseWrapper.get("response");

    String clientId = null;
    String clientSecret = null;

    try {
        clientId = AndroidJsonUtils.getExpectedStringValue(discoveryResponseJsonNode, "client_id");
    } catch (final NoFieldException e) {
        e.printStackTrace();
    }
    Log.d(TAG, "clientId = " + clientId);

    try {
        clientSecret = AndroidJsonUtils.getExpectedStringValue(discoveryResponseJsonNode, "client_secret");
    } catch (final NoFieldException e) {
        e.printStackTrace();
    }
    Log.d(TAG, "clientSecret = " + clientSecret);

    try {
        Log.d(TAG, "clientSecret = " + clientId);
        Log.d(TAG, "authUri = " + authUri);
        Log.d(TAG, "responseType = code");
        Log.d(TAG, "clientId = " + clientSecret);
        Log.d(TAG, "scopes = " + scopes);
        Log.d(TAG, "returnUri = " + redirectUri);
        Log.d(TAG, "state = " + state);
        Log.d(TAG, "nonce = " + nonce);
        Log.d(TAG, "maxAge = " + maxAge);
        Log.d(TAG, "acrValues = " + acrValues);

        if (authUri == null) {
            authUri = "";
        }
        String requestUri = authUri;
        if (authUri.indexOf("?") == -1) {
            requestUri += "?";
        } else if (authUri.indexOf("&") == -1) {
            requestUri += "&";
        }
        final String charSet = Charset.defaultCharset().name();
        requestUri += "response_type=" + URLEncoder.encode("code", charSet);
        requestUri += "&client_id=" + URLEncoder.encode(clientId, charSet);
        requestUri += "&scope=" + URLEncoder.encode(scopes, charSet);
        requestUri += "&redirect_uri=" + URLEncoder.encode(redirectUri, charSet);
        requestUri += "&state=" + URLEncoder.encode(state, charSet);
        requestUri += "&nonce=" + URLEncoder.encode(nonce, charSet);
        //  requestUri += "&prompt=" + URLEncoder.encode(prompt.value(), charSet);
        requestUri += "&max_age=" + URLEncoder.encode(Integer.toString(maxAge), charSet);
        requestUri += "&acr_values=" + URLEncoder.encode(acrValues);

        if (hmapExtraOptions != null && hmapExtraOptions.size() > 0) {
            for (final String key : hmapExtraOptions.keySet()) {
                requestUri += "&" + key + "="
                        + URLEncoder.encode(hmapExtraOptions.get(key).toString(), charSet);
            }
        }

        final RelativeLayout webViewLayout = (RelativeLayout) LayoutInflater.from(context)
                .inflate(R.layout.layout_web_view, null);

        final InteractableWebView webView = (InteractableWebView) webViewLayout.findViewById(R.id.web_view);
        final ProgressBar progressBar = (ProgressBar) webViewLayout.findViewById(R.id.progressBar);

        final DiscoveryAuthenticationDialog dialog = new DiscoveryAuthenticationDialog(context);

        if (webView.getParent() != null) {
            ((ViewGroup) webView.getParent()).removeView(webView);
        }

        dialog.setContentView(webView);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onCloseWindow(final WebView w) {
                super.onCloseWindow(w);
                Log.d(TAG, "Window close");
                w.setVisibility(View.INVISIBLE);
                w.destroy();
            }
        });

        final AuthorizationWebViewClient client = new AuthorizationWebViewClient(dialog, progressBar, listener,
                redirectUri, config, response);
        webView.setWebViewClient(client);

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(final DialogInterface dialogInterface) {
                Log.e("Auth Dialog", "dismissed");
                dialogInterface.dismiss();
                closeWebViewAndNotify(listener, webView);
            }
        });

        webView.loadUrl(requestUri);

        try {
            dialog.show();
        } catch (final WindowManager.BadTokenException exception) {
            Log.e("Discovery Dialog", exception.getMessage());
        }
    } catch (final NullPointerException e) {
        Log.d(TAG, "NullPointerException=" + e.getMessage(), e);
    }
}

From source file:com.azure.webapi.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * /*from   w w  w .ja va 2 s .com*/
 * @param provider
 *            The provider used for the authentication process
 * @param startUrl
 *            The initial URL for the authentication process
 * @param endUrl
 *            The final URL for the authentication process
 * @param context
 *            The context used to create the authentication dialog
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
protected void showLoginUI(MobileServiceAuthenticationProvider provider, final String startUrl,
        final String endUrl, final Context context, LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setTitle("Connecting to a service");
    builder.setCancelable(true);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });

    // Set cancel button's action
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
            wv.destroy();
        }
    });

    wv.getSettings().setJavaScriptEnabled(true);

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished
            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:android.webkit.cts.WebViewTest.java

@UiThreadTest
public void testDestroy() {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;/*from w  w  w  .ja v a 2 s .c  o m*/
    }
    // Create a new WebView, since we cannot call destroy() on a view in the hierarchy
    WebView localWebView = new WebView(getActivity());
    localWebView.destroy();
}

From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java

private Cookie checkAntiDDOS(final CloudflareException exception, final HttpHost proxy, CancellableTask task,
        final Activity activity) {
    synchronized (lock) {
        if (processing)
            return null;
        processing = true;//w ww  .j a va2 s. c o  m
    }
    processing2 = true;
    currentCookie = null;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(activity);
        CookieManager.getInstance().removeAllCookie();
    } else {
        CompatibilityImpl.clearCookies(CookieManager.getInstance());
    }

    final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView();
    final WebViewClient client = new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            Logger.d(TAG, "Got Page: " + url);
            String value = null;
            try {
                String[] cookies = CookieManager.getInstance().getCookie(url).split("[;]");
                for (String cookie : cookies) {
                    if ((cookie != null) && (!cookie.trim().equals(""))
                            && (cookie.startsWith(" " + exception.getRequiredCookieName() + "="))) {
                        value = cookie.substring(exception.getRequiredCookieName().length() + 2);
                    }
                }
            } catch (NullPointerException e) {
                Logger.e(TAG, e);
            }
            if (value != null) {
                BasicClientCookieHC4 cf_cookie = new BasicClientCookieHC4(exception.getRequiredCookieName(),
                        value);
                cf_cookie.setDomain("." + Uri.parse(url).getHost());
                cf_cookie.setPath("/");
                currentCookie = cf_cookie;
                Logger.d(TAG, "Cookie found: " + value);
                processing2 = false;
            } else {
                Logger.d(TAG, "Cookie is not found");
            }
        }
    };

    activity.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            webView = new WebView(activity);
            webView.setVisibility(View.GONE);
            layout.addView(webView);
            webView.setWebViewClient(client);
            webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING);
            webView.getSettings().setJavaScriptEnabled(true);
            webViewContext = webView.getContext();
            if (proxy != null)
                WebViewProxy.setProxy(webViewContext, proxy.getHostName(), proxy.getPort());
            webView.loadUrl(exception.getCheckUrl());
        }
    });

    long startTime = System.currentTimeMillis();
    while (processing2) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > TIMEOUT) {
            processing2 = false;
        }
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                layout.removeView(webView);
                webView.stopLoading();
                webView.clearCache(true);
                webView.destroy();
                webView = null;
            } finally {
                if (proxy != null)
                    WebViewProxy.setProxy(webViewContext, null, 0);
                processing = false;
            }
        }
    });

    return currentCookie;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private String getUserAgent() {
    try {/*from w  ww . j  a v  a  2  s .c  o m*/
        String userAgent = System.getProperty("http.agent");
        if (userAgent != null) {
            return userAgent;
        }
    } catch (Exception e) {
    }
    if (getActivity() == null) {
        return "Android-CN1";
    }
    try {
        Constructor<WebSettings> constructor = WebSettings.class.getDeclaredConstructor(Context.class,
                WebView.class);
        constructor.setAccessible(true);
        try {
            WebSettings settings = constructor.newInstance(getActivity(), null);
            return settings.getUserAgentString();
        } finally {
            constructor.setAccessible(false);
        }
    } catch (Exception e) {
        final StringBuffer ua = new StringBuffer();
        if (Thread.currentThread().getName().equalsIgnoreCase("main")) {
            WebView m_webview = new WebView(getActivity());
            ua.append(m_webview.getSettings().getUserAgentString());
            m_webview.destroy();
        } else {
            final boolean[] flag = new boolean[1];
            Thread thread = new Thread() {
                public void run() {
                    Looper.prepare();
                    WebView m_webview = new WebView(getActivity());
                    ua.append(m_webview.getSettings().getUserAgentString());
                    m_webview.destroy();
                    Looper.loop();
                    flag[0] = true;
                    synchronized (flag) {
                        flag.notify();
                    }
                }
            };
            thread.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
            thread.start();
            while (!flag[0]) {
                synchronized (flag) {
                    try {
                        flag.wait(100);
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }
        return ua.toString();
    }
}