List of usage examples for android.webkit WebViewClient WebViewClient
WebViewClient
From source file:com.ibuildapp.romanblack.CataloguePlugin.ProductDetails.java
/** * Initializing user interface/*from ww w. j a v a 2s .c o m*/ */ private void initializeUI() { setContentView(R.layout.details_layout); hideTopBar(); navBarHolder = (RelativeLayout) findViewById(R.id.navbar_holder); List<String> imageUrls = new ArrayList<>(); imageUrls.add(product.imageURL); imageUrls.addAll(product.imageUrls); final float density = getResources().getDisplayMetrics().density; int topBarHeight = (int) (TOP_BAR_HEIGHT * density); TextView apply_button = (TextView) findViewById(R.id.apply_button); View basket = findViewById(R.id.basket); View bottomSeparator = findViewById(R.id.bottom_separator); quantity = (EditText) findViewById(R.id.quantity); roundsList = (RecyclerView) findViewById(R.id.details_recyclerview); if (imageUrls.size() <= 1) roundsList.setVisibility(View.GONE); LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); roundsList.setLayoutManager(layoutManager); pager = (ViewPager) findViewById(R.id.viewpager); if (!"".equals(imageUrls.get(0))) { final RoundAdapter rAdapter = new RoundAdapter(this, imageUrls); roundsList.setAdapter(rAdapter); float width = getResources().getDisplayMetrics().widthPixels; float height = getResources().getDisplayMetrics().heightPixels; height -= 2 * topBarHeight; height -= com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.getStatusBarHeight(this); pager.getLayoutParams().width = (int) width; pager.getLayoutParams().height = (int) height; newCurrentItem = 0; pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { oldCurrentItem = newCurrentItem; newCurrentItem = position; rAdapter.setCurrentItem(newCurrentItem); rAdapter.notifyItemChanged(newCurrentItem); if (oldCurrentItem != -1) rAdapter.notifyItemChanged(oldCurrentItem); } @Override public void onPageScrollStateChanged(int state) { } }); pager.setPageTransformer(true, new InnerPageTransformer()); adapter = new DetailsViewPagerAdapter(getSupportFragmentManager(), imageUrls); roundsList.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int totalWidth = (int) (adapter.getCount() * 21 * density); int screenWidth = getResources().getDisplayMetrics().widthPixels; int position = parent.getChildAdapterPosition(view); if ((totalWidth < screenWidth) && position == 0) outRect.left = (screenWidth - totalWidth) / 2; } }); pager.setAdapter(adapter); } else { roundsList.setVisibility(View.GONE); pager.setVisibility(View.GONE); } buyLayout = (RelativeLayout) findViewById(R.id.details_buy_layout); if (product.itemType.equals(ProductItemType.EXTERNAL)) quantity.setVisibility(View.GONE); else quantity.setVisibility(View.VISIBLE); if (Statics.isBasket) { buyLayout.setVisibility(View.VISIBLE); onShoppingCartItemAdded(); apply_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { hideKeyboard(); quantity.setText(StringUtils.isBlank(quantity.getText().toString()) ? "1" : quantity.getText().toString()); quantity.clearFocus(); String message = ""; int quant = Integer.valueOf(quantity.getText().toString()); List<ShoppingCart.Product> products = ShoppingCart.getProducts(); int count = 0; for (ShoppingCart.Product product : products) count += product.getQuantity(); try { message = new PluralResources(getResources()).getQuantityString(R.plurals.items_to_cart, count + quant, count + quant); } catch (NoSuchMethodException e) { e.printStackTrace(); } int index = products.indexOf(new ShoppingCart.Product.Builder().setId(product.id).build()); ShoppingCart.insertProduct(new ShoppingCart.Product.Builder().setId(product.id) .setQuantity((index == -1 ? 0 : products.get(index).getQuantity()) + quant).build()); onShoppingCartItemAdded(); com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.showDialog(ProductDetails.this, R.string.shopping_cart_dialog_title, message, R.string.shopping_cart_dialog_continue, R.string.shopping_cart_dialog_view_cart, new com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.OnDialogButtonClickListener() { @Override public void onPositiveClick(DialogInterface dialog) { dialog.dismiss(); } @Override public void onNegativeClick(DialogInterface dialog) { Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class); ProductDetails.this.startActivity(intent); } }); } }); if (product.itemType.equals(ProductItemType.EXTERNAL)) { basket.setVisibility(View.GONE); apply_button.setText(product.itemButtonText); apply_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class); intent.putExtra("itemUrl", product.itemUrl); startActivity(intent); } }); } else { basket.setVisibility(View.VISIBLE); apply_button.setText(R.string.shopping_cart_add_to_cart); } } else { if (product.itemType.equals(ProductItemType.EXTERNAL)) buyLayout.setVisibility(View.VISIBLE); else buyLayout.setVisibility(View.GONE); apply_button.setText(R.string.buy_now); basket.setVisibility(View.GONE); findViewById(R.id.cart_items).setVisibility(View.GONE); /*apply_button_padding_left = 0; apply_button.setGravity(Gravity.CENTER); apply_button.setPadding(apply_button_padding_left, 0, 0, 0);*/ if (TextUtils.isEmpty(Statics.PAYPAL_CLIENT_ID) || product.price == 0) { bottomSeparator.setVisibility(View.GONE); apply_button.setVisibility(View.GONE); basket.setVisibility(View.GONE); } else { apply_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { payer.singlePayment(new Payer.Item.Builder().setPrice(product.price) .setCurrencyCode(Payer.CurrencyCode.valueOf(Statics.uiConfig.currency)) .setName(product.name).setEndpoint(Statics.ENDPOINT).setAppId(Statics.appId) .setWidgetId(Statics.widgetId).setItemId(product.item_id).build()); } }); } if (product.itemType.equals(ProductItemType.EXTERNAL)) { basket.setVisibility(View.GONE); apply_button.setText(product.itemButtonText); apply_button.setVisibility(View.VISIBLE); apply_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class); intent.putExtra("itemUrl", product.itemUrl); startActivity(intent); } }); } } backBtn = (LinearLayout) findViewById(R.id.back_btn); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); title = (TextView) findViewById(R.id.title_text); title.setMaxWidth((int) (screenWidth * 0.55)); if (category != null && !TextUtils.isEmpty(category.name)) title.setText(category.name); View basketBtn = findViewById(R.id.basket_view_btn); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class); startActivity(intent); } }; basketBtn.setOnClickListener(listener); View hamburgerView = findViewById(R.id.hamburger_view_btn); hamburgerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { animateRootContainer(); } }); if (!showSideBar) { hamburgerView.setVisibility(View.GONE); basketBtn.setVisibility(View.VISIBLE); basketBtn.setVisibility(Statics.isBasket ? View.VISIBLE : View.GONE); findViewById(R.id.cart_items).setVisibility(View.VISIBLE); } else { hamburgerView.setVisibility(View.VISIBLE); findViewById(R.id.cart_items).setVisibility(View.INVISIBLE); basketBtn.setVisibility(View.GONE); if (Statics.isBasket) shopingCartIndex = setTopBarRightButton(basketBtn, getResources().getString(R.string.shopping_cart), listener); } productTitle = (TextView) findViewById(R.id.product_title); productTitle.setText(product.name); product_sku = (TextView) findViewById(R.id.product_sku); if (TextUtils.isEmpty(product.sku)) { product_sku.setVisibility(View.GONE); product_sku.setText(""); } else { product_sku.setVisibility(View.VISIBLE); product_sku.setText(getString(R.string.item_sku) + " " + product.sku); } productDescription = (WebView) findViewById(R.id.product_description); productDescription.getSettings().setJavaScriptEnabled(true); productDescription.getSettings().setDomStorageEnabled(true); productDescription.setWebChromeClient(new WebChromeClient()); productDescription.setWebViewClient(new WebViewClient() { @Override public void onLoadResource(WebView view, String url) { if (!alreadyLoaded && (url.startsWith("http://www.youtube.com/get_video_info?") || url.startsWith("https://www.youtube.com/get_video_info?")) && Build.VERSION.SDK_INT <= 11) { try { String path = url.contains("https://www.youtube.com/get_video_info?") ? url.replace("https://www.youtube.com/get_video_info?", "") : url.replace("http://www.youtube.com/get_video_info?", ""); String[] parqamValuePairs = path.split("&"); String videoId = null; for (String pair : parqamValuePairs) { if (pair.startsWith("video_id")) { videoId = pair.split("=")[1]; break; } } if (videoId != null) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")) .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId))); alreadyLoaded = !alreadyLoaded; } } catch (Exception ex) { } } else { super.onLoadResource(view, url); } } @Override public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) { final AlertDialog.Builder builder = new AlertDialog.Builder(ProductDetails.this); builder.setMessage(R.string.catalog_notification_error_ssl_cert_invalid); builder.setPositiveButton(ProductDetails.this.getResources().getString(R.string.catalog_continue), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handler.proceed(); } }); builder.setNegativeButton(ProductDetails.this.getResources().getString(R.string.catalog_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handler.cancel(); } }); final AlertDialog dialog = builder.create(); dialog.show(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { if (url.contains("youtube.com/embed")) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")) .setData(Uri.parse(url))); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("tel:")) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url)); startActivity(intent); return true; } else if (url.startsWith("mailto:")) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url)); startActivity(intent); return true; } else if (url.contains("youtube.com")) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")) .setData(Uri.parse(url))); return true; } catch (Exception ex) { return false; } } else if (url.contains("goo.gl") || url.contains("maps") || url.contains("maps.yandex") || url.contains("livegpstracks")) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url))); return true; } else { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url))); return true; } } }); productDescription.loadDataWithBaseURL(null, product.description, "text/html", "UTF-8", null); productPrice = (TextView) findViewById(R.id.product_price); productPrice.setVisibility( "0.00".equals(String.format(Locale.US, "%.2f", product.price)) ? View.GONE : View.VISIBLE); String result = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils .currencyToPosition(Statics.uiConfig.currency, product.price); if (result.contains(getResources().getString(R.string.rest_number_pattern))) result = result.replace(getResources().getString(R.string.rest_number_pattern), ""); productPrice.setText(result); likeCount = (TextView) findViewById(R.id.like_count); likeImage = (ImageView) findViewById(R.id.like_image); if (!TextUtils.isEmpty(product.imageURL)) { new Thread(new Runnable() { @Override public void run() { String token = FacebookAuthorizationActivity.getFbToken( com.appbuilder.sdk.android.Statics.FACEBOOK_APP_ID, com.appbuilder.sdk.android.Statics.FACEBOOK_APP_SECRET); if (TextUtils.isEmpty(token)) return; List<String> urls = new ArrayList<String>(); urls.add(product.imageURL); final Map<String, String> res = FacebookAuthorizationActivity.getLikesForUrls(urls, token); if (res != null) { runOnUiThread(new Runnable() { @Override public void run() { likeCount.setText(res.get(product.imageURL)); } }); } Log.e("", ""); } }).start(); } shareBtn = (LinearLayout) findViewById(R.id.share_button); if (Statics.uiConfig.showShareButton) shareBtn.setVisibility(View.VISIBLE); else shareBtn.setVisibility(View.GONE); shareBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialogSharing(new DialogSharing.Configuration.Builder() .setFacebookSharingClickListener(new DialogSharing.Item.OnClickListener() { @Override public void onClick() { // checking Internet connection if (!Utils.networkAvailable(ProductDetails.this)) Toast.makeText(ProductDetails.this, getResources().getString(R.string.alert_no_internet), Toast.LENGTH_SHORT).show(); else { if (Authorization .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK) != null) { shareFacebook(); } else { Authorization.authorize(ProductDetails.this, FACEBOOK_AUTHORIZATION_ACTIVITY, Authorization.AUTHORIZATION_TYPE_FACEBOOK); } } } }).setTwitterSharingClickListener(new DialogSharing.Item.OnClickListener() { @Override public void onClick() { // checking Internet connection if (!Utils.networkAvailable(ProductDetails.this)) Toast.makeText(ProductDetails.this, getResources().getString(R.string.alert_no_internet), Toast.LENGTH_SHORT).show(); else { if (Authorization .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_TWITTER) != null) { shareTwitter(); } else { Authorization.authorize(ProductDetails.this, TWITTER_AUTHORIZATION_ACTIVITY, Authorization.AUTHORIZATION_TYPE_TWITTER); } } } }).setEmailSharingClickListener(new DialogSharing.Item.OnClickListener() { @Override public void onClick() { Intent intent = chooseEmailClient(); intent.setType("text/html"); // ************************************************************************************************* // preparing sharing message String downloadThe = getString(R.string.directoryplugin_email_download_this); String androidIphoneApp = getString( R.string.directoryplugin_email_android_iphone_app); String postedVia = getString(R.string.directoryplugin_email_posted_via); String foundThis = getString(R.string.directoryplugin_email_found_this); // prepare content String downloadAppUrl = String.format( "http://%s/projects.php?action=info&projectid=%s", com.appbuilder.sdk.android.Statics.BASE_DOMEN, Statics.appId); String adPart = String.format( downloadThe + " %s " + androidIphoneApp + ": <a href=\"%s\">%s</a><br>%s", Statics.appName, downloadAppUrl, downloadAppUrl, postedVia + " <a href=\"http://ibuildapp.com\">www.ibuildapp.com</a>"); // content part String contentPath = String.format( "<!DOCTYPE html><html><body><b>%s</b><br><br>%s<br><br>%s</body></html>", product.name, product.description, com.ibuildapp.romanblack.CataloguePlugin.Statics.hasAd ? adPart : ""); contentPath = contentPath.replaceAll("\\<img.*?>", ""); // prepare image to attach // FROM ASSETS InputStream stream = null; try { if (!TextUtils.isEmpty(product.imageRes)) { stream = manager.open(product.imageRes); String fileName = inputStreamToFile(stream); File copyTo = new File(fileName); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo)); } } catch (IOException e) { // from cache File copyTo = new File(product.imagePath); if (copyTo.exists()) { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo)); } } intent.putExtra(Intent.EXTRA_SUBJECT, product.name); intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(contentPath)); startActivity(intent); } }).build()); // openOptionsMenu(); } }); likeBtn = (LinearLayout) findViewById(R.id.like_button); if (Statics.uiConfig.showLikeButton) likeBtn.setVisibility(View.VISIBLE); else likeBtn.setVisibility(View.GONE); likeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Utils.networkAvailable(ProductDetails.this)) { if (!TextUtils.isEmpty(product.imageURL)) { if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) { new Thread(new Runnable() { @Override public void run() { List<String> userLikes = null; try { userLikes = FacebookAuthorizationActivity.getUserOgLikes(); for (String likeUrl : userLikes) { if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) { likedbyMe = true; break; } } if (!likedbyMe) { if (FacebookAuthorizationActivity.like(product.imageURL)) { String likeCountStr = likeCount.getText().toString(); try { final int res = Integer.parseInt(likeCountStr); runOnUiThread(new Runnable() { @Override public void run() { likeCount.setText(Integer.toString(res + 1)); enableLikeButton(false); Toast.makeText(ProductDetails.this, getString(R.string.like_success), Toast.LENGTH_SHORT).show(); } }); } catch (NumberFormatException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ProductDetails.this, getString(R.string.like_error), Toast.LENGTH_SHORT).show(); } }); } } } else { runOnUiThread(new Runnable() { @Override public void run() { enableLikeButton(false); Toast.makeText(ProductDetails.this, getString(R.string.already_liked), Toast.LENGTH_SHORT) .show(); } }); } } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) { if (!Utils.networkAvailable(ProductDetails.this)) { Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet), Toast.LENGTH_SHORT) .show(); return; } Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB, Authorization.AUTHORIZATION_TYPE_FACEBOOK); } catch (FacebookAuthorizationActivity.FacebookAlreadyLiked facebookAlreadyLiked) { facebookAlreadyLiked.printStackTrace(); } } }).start(); } else { if (!Utils.networkAvailable(ProductDetails.this)) { Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet), Toast.LENGTH_SHORT).show(); return; } Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB, Authorization.AUTHORIZATION_TYPE_FACEBOOK); } } else Toast.makeText(ProductDetails.this, getString(R.string.nothing_to_like), Toast.LENGTH_SHORT) .show(); } else Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet), Toast.LENGTH_SHORT) .show(); } }); if (TextUtils.isEmpty(product.imageURL)) { enableLikeButton(false); } else { if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) { new Thread(new Runnable() { @Override public void run() { List<String> userLikes = null; try { userLikes = FacebookAuthorizationActivity.getUserOgLikes(); for (String likeUrl : userLikes) { if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) { likedbyMe = true; break; } } runOnUiThread(new Runnable() { @Override public void run() { enableLikeButton(!likedbyMe); } }); } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) { e.printStackTrace(); } } }).start(); } } // product bitmap rendering image = (AlphaImageView) findViewById(R.id.product_image); image.setVisibility(View.GONE); if (!TextUtils.isEmpty(product.imageRes)) { try { InputStream input = manager.open(product.imageRes); Bitmap btm = BitmapFactory.decodeStream(input); if (btm != null) { int ratio = btm.getWidth() / btm.getHeight(); image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, screenWidth / ratio)); image.setImageBitmapWithAlpha(btm); //image.setImageBitmap(btm); return; } } catch (IOException e) { } } if (!TextUtils.isEmpty(product.imagePath)) { Bitmap btm = BitmapFactory.decodeFile(product.imagePath); if (btm != null) { if (btm.getWidth() != 0 && btm.getHeight() != 0) { float ratio = (float) btm.getWidth() / (float) btm.getHeight(); image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, (int) (screenWidth / ratio))); image.setImageBitmapWithAlpha(btm); image.setVisibility(View.GONE); return; } } } if (!TextUtils.isEmpty(product.imageURL)) { new Thread(new Runnable() { @Override public void run() { product.imagePath = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils .downloadFile(product.imageURL); if (!TextUtils.isEmpty(product.imagePath)) { SqlAdapter.updateProduct(product); final Bitmap btm = BitmapFactory.decodeFile(product.imagePath); if (btm != null) { runOnUiThread(new Runnable() { @Override public void run() { if (btm.getWidth() != 0 && btm.getHeight() != 0) { float ratio = (float) btm.getWidth() / (float) btm.getHeight(); image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, (int) (screenWidth / ratio))); image.setImageBitmapWithAlpha(btm); image.setVisibility(View.GONE); } } }); } } } }).start(); } image.setVisibility(View.GONE); }
From source file:com.slarker.tech.hi0734.view.widget.webview.AdvancedWebView.java
@SuppressLint({ "SetJavaScriptEnabled" }) protected void init(Context context) { // in IDE's preview mode if (isInEditMode()) { // do not run the code from this method return;//from w w w . ja v a 2 s. c o m } if (context instanceof Activity) { mActivity = new WeakReference<Activity>((Activity) context); } mLanguageIso3 = getLanguageIso3(); setFocusable(true); setFocusableInTouchMode(true); setSaveEnabled(true); final String filesDir = context.getFilesDir().getPath(); final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER; final WebSettings webSettings = getSettings(); webSettings.setAllowFileAccess(false); setAllowAccessFromFileUrls(webSettings, false); webSettings.setBuiltInZoomControls(false); webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setUserAgentString(ApiClientHelper.getUserAgent((AppContext) x.app()) + "/isapp"); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { // Hide the zoom controls for HONEYCOMB+ webSettings.setDisplayZoomControls(false); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } if (Build.VERSION.SDK_INT < 18) { webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); } webSettings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT < 19) { webSettings.setDatabasePath(databaseDir); } setMixedContentAllowed(webSettings, true); setThirdPartyCookiesEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); super.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { if (!hasError()) { if (mListener != null) { mListener.onPageStarted(url, favicon); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageStarted(view, url, favicon); } } @Override public void onPageFinished(WebView view, String url) { if (!hasError()) { if (mListener != null) { mListener.onPageFinished(url); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageFinished(view, url); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { setLastError(); if (mListener != null) { mListener.onPageError(errorCode, description, failingUrl); } if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl); } } @Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) { // if the hostname may not be accessed if (!isHostnameAllowed(url)) { // if a listener is available if (mListener != null) { // inform the listener about the request mListener.onExternalPageRequest(url); } // cancel the original request return true; } // if there is a user-specified handler available if (mCustomWebViewClient != null) { // if the user-specified handler asks to override the request if (mCustomWebViewClient.shouldOverrideUrlLoading(view, url)) { // cancel the original request return true; } } // route the request through the custom URL loading method view.loadUrl(url); // cancel the original request return true; } @Override public void onLoadResource(WebView view, String url) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onLoadResource(view, url); } else { super.onLoadResource(view, url); } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (Build.VERSION.SDK_INT >= 11) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, url); } else { return super.shouldInterceptRequest(view, url); } } else { return null; } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, request); } else { return super.shouldInterceptRequest(view, request); } } else { return null; } } @Override public void onFormResubmission(WebView view, Message dontResend, Message resend) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onFormResubmission(view, dontResend, resend); } else { super.onFormResubmission(view, dontResend, resend); } } @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { if (mCustomWebViewClient != null) { mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload); } else { super.doUpdateVisitedHistory(view, url, isReload); } } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedSslError(view, handler, error); } else { super.onReceivedSslError(view, handler, error); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedClientCertRequest(view, request); } else { super.onReceivedClientCertRequest(view, request); } } } @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); } else { super.onReceivedHttpAuthRequest(view, handler, host, realm); } } @Override public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldOverrideKeyEvent(view, event); } else { return super.shouldOverrideKeyEvent(view, event); } } @Override public void onUnhandledKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onUnhandledKeyEvent(view, event); } else { super.onUnhandledKeyEvent(view, event); } } @SuppressLint("NewApi") @SuppressWarnings("all") @TargetApi(21) public void onUnhandledInputEvent(WebView view, InputEvent event) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { // mCustomWebViewClient.onUnhandledInputEvent(view, event); } else { // super.onUnhandledInputEvent(view, event); } } } @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onScaleChanged(view, oldScale, newScale); } else { super.onScaleChanged(view, oldScale, newScale); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedLoginRequest(WebView view, String realm, String account, String args) { if (Build.VERSION.SDK_INT >= 12) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args); } else { super.onReceivedLoginRequest(view, realm, account, args); } } } }); super.setWebChromeClient(new WebChromeClient() { // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg) { openFileChooser(uploadMsg, null); } // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method) public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { openFileChooser(uploadMsg, acceptType, null); } // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { openFileInput(uploadMsg, null, false); } // file upload callback (Android 5.0 (API level 21) -- current) (public method) @SuppressWarnings("all") public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (Build.VERSION.SDK_INT >= 21) { final boolean allowMultiple = fileChooserParams .getMode() == FileChooserParams.MODE_OPEN_MULTIPLE; openFileInput(null, filePathCallback, allowMultiple); return true; } else { return false; } } @Override public void onProgressChanged(WebView view, int newProgress) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onProgressChanged(view, newProgress); } else { super.onProgressChanged(view, newProgress); } } @Override public void onReceivedTitle(WebView view, String title) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTitle(view, title); } else { super.onReceivedTitle(view, title); } } @Override public void onReceivedIcon(WebView view, Bitmap icon) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedIcon(view, icon); } else { super.onReceivedIcon(view, icon); } } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed); } else { super.onReceivedTouchIconUrl(view, url, precomposed); } } @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, callback); } else { super.onShowCustomView(view, callback); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { if (Build.VERSION.SDK_INT >= 14) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback); } else { super.onShowCustomView(view, requestedOrientation, callback); } } } @Override public void onHideCustomView() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onHideCustomView(); } else { super.onHideCustomView(); } } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } else { return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } } @Override public void onRequestFocus(WebView view) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onRequestFocus(view); } else { super.onRequestFocus(view); } } @Override public void onCloseWindow(WebView window) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onCloseWindow(window); } else { super.onCloseWindow(window); } } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsAlert(view, url, message, result); } else { return super.onJsAlert(view, url, message, result); } } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsConfirm(view, url, message, result); } else { return super.onJsConfirm(view, url, message, result); } } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result); } else { return super.onJsPrompt(view, url, message, defaultValue, result); } } @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result); } else { return super.onJsBeforeUnload(view, url, message, result); } } @Override public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { if (mGeolocationEnabled) { callback.invoke(origin, true, false); } else { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback); } else { super.onGeolocationPermissionsShowPrompt(origin, callback); } } } @Override public void onGeolocationPermissionsHidePrompt() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsHidePrompt(); } else { super.onGeolocationPermissionsHidePrompt(); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequest(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequest(request); } else { super.onPermissionRequest(request); } } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequestCanceled(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequestCanceled(request); } else { super.onPermissionRequestCanceled(request); } } } @Override public boolean onJsTimeout() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsTimeout(); } else { return super.onJsTimeout(); } } @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID); } else { super.onConsoleMessage(message, lineNumber, sourceID); } } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onConsoleMessage(consoleMessage); } else { return super.onConsoleMessage(consoleMessage); } } @Override public Bitmap getDefaultVideoPoster() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getDefaultVideoPoster(); } else { return super.getDefaultVideoPoster(); } } @Override public View getVideoLoadingProgressView() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getVideoLoadingProgressView(); } else { return super.getVideoLoadingProgressView(); } } @Override public void getVisitedHistory(ValueCallback<String[]> callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.getVisitedHistory(callback); } else { super.getVisitedHistory(callback); } } @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } else { super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } } @Override public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } else { super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } } }); setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(final String url, final String userAgent, final String contentDisposition, final String mimeType, final long contentLength) { final String suggestedFilename = URLUtil.guessFileName(url, contentDisposition, mimeType); if (mListener != null) { mListener.onDownloadRequested(url, suggestedFilename, mimeType, contentLength, contentDisposition, userAgent); } } }); }
From source file:com.timemachine.controller.ControllerActivity.java
private void setupUI() { // Set layout listener View controllerView = findViewById(R.id.controllerView); ViewTreeObserver vto = controllerView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override/* w w w .j a v a 2s . co m*/ public void onGlobalLayout() { runOnUiThread(new Runnable() { public void run() { locationSliderHeight = locationSlider.getHeight(); originLocationSliderContainerY = locationSliderContainer.getY(); originPlayPauseButtonY = playPause.getY(); minLocationSliderContainerY = originLocationSliderContainerY; maxLocationSliderContainerY = originLocationSliderContainerY + locationSliderHeight; midLocationSliderContainerY = (minLocationSliderContainerY + maxLocationSliderContainerY) / 2; } }); System.out.println("locationSliderHeight: " + locationSliderHeight); System.out.println("locationSliderContainerY: " + originLocationSliderContainerY); locationSlider.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); // Connect to controller.html controllerURL = "http://" + ipText + ":8080/controller.html"; locationSlider = (WebView) findViewById(R.id.webview); locationSliderContainer = (FrameLayout) findViewById(R.id.sliderContainer); locationSlider.setBackgroundColor(Color.TRANSPARENT); locationSlider.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); locationSlider.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { System.out.println("onReceivedError"); showConnectDialog("Error while connecting to controller. Connect again."); } @Override public void onLoadResource(WebView view, String url) { if (url.contains("thumbnail")) isMasterConnected = true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { isMasterConnectedTimerTask = null; isMasterConnectedTimerTask = new TimerTask() { @Override public void run() { if (isMasterConnected == false) showConnectDialog("Master is not loaded in the browser. Connect again."); } }; isMasterConnectedTimer.schedule(isMasterConnectedTimerTask, 6000); } @Override public void onPageFinished(WebView view, String url) { if (url.contains(controllerURL)) { drag.setVisibility(View.VISIBLE); playPause.setVisibility(View.VISIBLE); loadPreferences(); } super.onPageFinished(view, url); } }); try { locationSlider.loadUrl(controllerURL); } catch (Exception e) { e.printStackTrace(); } // Set JavaScript Interface locationSlider.addJavascriptInterface(this, "androidObject"); WebSettings webSettings = locationSlider.getSettings(); webSettings.setJavaScriptEnabled(true); // Set the play-pause button playPause = (ImageButton) findViewById(R.id.playPauseButton); playPause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { socket.emit("handlePlayPauseServer"); } }); socket.emit("setControllerPlayButton"); // Set the drag button drag = (ImageButton) findViewById(R.id.drag); drag.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dragYDiffBetweenFingerAndSliderTop = locationSliderContainer.getY() - event.getRawY(); dragYDiffBetweenFingerAndPlayPauseTop = playPause.getY() - event.getRawY(); } if (event.getAction() == MotionEvent.ACTION_MOVE) { // Move the slider based on current finger location float newSliderY = event.getRawY() + dragYDiffBetweenFingerAndSliderTop; float newPlayPauseY = event.getRawY() + dragYDiffBetweenFingerAndPlayPauseTop; if (newSliderY > minLocationSliderContainerY && newSliderY < maxLocationSliderContainerY) { locationSliderContainer.setY(newSliderY); playPause.setY(newPlayPauseY); } } if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getEventTime() - event.getDownTime() <= tapTimeout) { // Tap is detected, toggle the slider System.out.println("onTap"); runOnUiThread(new Runnable() { public void run() { toggleSlider(); } }); } else { // Not a tap gesture, slide up or down based on the slider's current position if (locationSliderContainer.getY() > midLocationSliderContainerY) slideDown(); else slideUp(); } } return true; } }); // Set the Google map setUpMapIfNeeded(); }
From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java
public void oAuthRequest(String hostAndPath, String clientId, String scope) { Activity activity = getActivity();/* ww w . ja va2 s.c o m*/ if (activity == null) { return; } byte[] buf = new byte[16]; new Random().nextBytes(buf); mOAuthState = new String(Hex.encode(buf)); mOAuthCode = null; final Dialog auth_dialog = new Dialog(activity); auth_dialog.setContentView(R.layout.oauth_webview); WebView web = (WebView) auth_dialog.findViewById(R.id.web_view); web.getSettings().setSaveFormData(false); web.getSettings().setUserAgentString("OpenKeychain " + BuildConfig.VERSION_NAME); web.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if ("oauth-openkeychain".equals(uri.getScheme())) { if (mOAuthCode != null) { return true; } if (uri.getQueryParameter("error") != null) { Log.i(Constants.TAG, "got oauth error: " + uri.getQueryParameter("error")); auth_dialog.dismiss(); return true; } // check if mOAuthState == queryParam[state] mOAuthCode = uri.getQueryParameter("code"); auth_dialog.dismiss(); return true; } // don't surf away from github! if (!"github.com".equals(uri.getHost())) { auth_dialog.dismiss(); return true; } return false; } }); auth_dialog.setTitle(R.string.linked_webview_title_github); auth_dialog.setCancelable(true); auth_dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { step1GetOAuthToken(); } }); auth_dialog.show(); web.loadUrl("https://" + hostAndPath + "?client_id=" + clientId + "&scope=" + scope + "&redirect_uri=oauth-openkeychain://linked/" + "&state=" + mOAuthState); }
From source file:jahirfiquitiva.iconshowcase.fragments.DonationsFragment.java
/** * Build view for Flattr. see Flattr API for more information: * http://developers.flattr.net/button//*from w w w . j ava 2 s. co m*/ */ @SuppressLint("SetJavaScriptEnabled") @TargetApi(11) private void buildFlattrView() { final FrameLayout mLoadingFrame; final WebView mFlattrWebview; mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview); mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame); // disable hardware acceleration for this webview to get transparent background working if (Build.VERSION.SDK_INT >= 11) { mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // define own webview client to override loading behaviour mFlattrWebview.setWebViewClient(new WebViewClient() { /** * Open all links in browser, not in webview */ @Override public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } return false; } /** * Links in the flattr iframe should load in the browser not in the iframe itself, * http:/ * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the * -browser */ @Override public void onLoadResource(WebView view, String url) { if (url.contains("flattr")) { WebView.HitTestResult result = view.getHitTestResult(); if (result != null && result.getType() > 0) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } view.stopLoading(); } } } /** * After loading is done, remove frame with progress circle */ @Override public void onPageFinished(WebView view, String url) { // remove loading frame, show webview if (mLoadingFrame.getVisibility() == View.VISIBLE) { mLoadingFrame.setVisibility(View.GONE); mFlattrWebview.setVisibility(View.VISIBLE); } } }); // make text white and background transparent String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>"; // https is not working in android 2.1 and 2.2 String flattrScheme; if (Build.VERSION.SDK_INT >= 9) { flattrScheme = "https://"; } else { flattrScheme = "http://"; } // set url of flattr link TextView mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url); mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl); String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {" + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];" + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();" + "/* ]]> */" + "</script>"; String htmlMiddle = "</head> <body> <div align='center'>"; String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl + "' target='_blank'> <img src='" + flattrScheme + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>"; String htmlEnd = "</div> </body> </html>"; String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd; mFlattrWebview.getSettings().setJavaScriptEnabled(true); mFlattrWebview.loadData(flattrCode, "text/html", "utf-8"); // disable scroll on touch mFlattrWebview.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { // already handled (returns true) when moving return (motionEvent.getAction() == MotionEvent.ACTION_MOVE); } }); // make background of webview transparent // has to be called AFTER loadData // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2 mFlattrWebview.setBackgroundColor(0x00000000); }
From source file:org.sufficientlysecure.donations.DonationsFragment.java
/** * Build view for Flattr. see Flattr API for more information: * http://developers.flattr.net/button/// w w w .j av a 2 s . co m */ @SuppressLint("SetJavaScriptEnabled") @TargetApi(11) private void buildFlattrView() { final FrameLayout mLoadingFrame; final WebView mFlattrWebview; mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview); mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame); // disable hardware acceleration for this webview to get transparent background working if (Build.VERSION.SDK_INT >= 11) { mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // define own webview client to override loading behaviour mFlattrWebview.setWebViewClient(new WebViewClient() { /** * Open all links in browser, not in webview */ @Override public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } return false; } /** * Links in the flattr iframe should load in the browser not in the iframe itself, * http:/ * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the * -browser */ @Override public void onLoadResource(WebView view, String url) { if (url.contains("flattr")) { HitTestResult result = view.getHitTestResult(); if (result != null && result.getType() > 0) { try { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } catch (ActivityNotFoundException e) { openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title, getString(R.string.donations__alert_dialog_no_browser)); } view.stopLoading(); } } } /** * After loading is done, remove frame with progress circle */ @Override public void onPageFinished(WebView view, String url) { // remove loading frame, show webview if (mLoadingFrame.getVisibility() == View.VISIBLE) { mLoadingFrame.setVisibility(View.GONE); mFlattrWebview.setVisibility(View.VISIBLE); } } }); // make text white and background transparent String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>"; // https is not working in android 2.1 and 2.2 String flattrScheme; if (Build.VERSION.SDK_INT >= 9) { flattrScheme = "https://"; } else { flattrScheme = "http://"; } // set url of flattr link mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url); mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl); String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {" + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];" + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();" + "/* ]]> */" + "</script>"; String htmlMiddle = "</head> <body> <div align='center'>"; String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl + "' target='_blank'> <img src='" + flattrScheme + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>"; String htmlEnd = "</div> </body> </html>"; String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd; mFlattrWebview.getSettings().setJavaScriptEnabled(true); mFlattrWebview.loadData(flattrCode, "text/html", "utf-8"); // disable scroll on touch mFlattrWebview.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { // already handled (returns true) when moving return (motionEvent.getAction() == MotionEvent.ACTION_MOVE); } }); // make background of webview transparent // has to be called AFTER loadData // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2 mFlattrWebview.setBackgroundColor(0x00000000); }
From source file:com.free.searcher.MainFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup viewContainer, Bundle savedInstanceState) { super.onCreateView(inflater, viewContainer, savedInstanceState); this.activity = getActivity(); actionBar = activity.getActionBar(); View v = inflater.inflate(R.layout.main, viewContainer, false); v.setOnSystemUiVisibilityChangeListener(this); webView = (WebView) v.findViewById(R.id.webView1); statusView = (TextView) v.findViewById(R.id.statusView); if (webViewBundle != null) { webView.restoreState(webViewBundle); Log.d("onCreateView.webView.restoreState", webViewBundle + ""); } else if (currentUrl.length() > 0) { Log.d("onCreateView.locX, locY", locX + ", " + locY + ", " + currentUrl); webView.loadUrl(currentUrl);/* www.j a va2 s. c om*/ webView.setScrollX(locX); webView.setScrollY(locY); Log.d("currentUrl 8", currentUrl); } statusView.setText(status); Log.d("onCreateView.savedInstanceState", savedInstanceState + "vvv"); mNotificationManager = (NotificationManager) activity.getSystemService(activity.NOTIFICATION_SERVICE); webView.setFocusable(true); webView.setFocusableInTouchMode(true); webView.requestFocus(); webView.requestFocusFromTouch(); webView.getSettings().setAllowContentAccess(false); webView.getSettings().setPluginState(WebSettings.PluginState.OFF); // webView.setBackgroundColor(LIGHT_BLUE); webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webView.setBackgroundColor(getResources().getColor(R.color.lightyellow)); webView.setOnLongClickListener(this); statusView.setOnLongClickListener(this); webView.setWebViewClient(new WebViewClient() { private void jumpTo(final int xLocation, final int yLocation) { webView.postDelayed(new Runnable() { @Override public void run() { Log.d("jumpTo1.locX, locY", xLocation + ", " + yLocation + ", " + currentUrl); try { webView.scrollTo(xLocation, yLocation); webView.setScrollX(xLocation); webView.setScrollY(yLocation); // locX = 0; // locY = 0; } catch (RuntimeException e) { Log.e("error jumpTo2.locX, locY", locX + ", " + locY + ", " + currentUrl); } } }, 100); } @Override public boolean shouldOverrideUrlLoading(WebView view, final String url) { if (currentZipFileName.length() > 0 && (extractFile == null || extractFile.isClosed())) { try { extractFile = new ExtractFile(currentZipFileName, MainFragment.PRIVATE_PATH + currentZipFileName); } catch (RarException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } int ind = url.indexOf("?deleteFile="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String selectedFile = urlStatus.substring(urlStatus.indexOf("?deleteFile=") + 12, urlStatus.length()); Log.d("deleteFile", "url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete File?"); alert.setMessage("Do you really want to delete file \"" + selectedFile + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.loadUrl( new File(dupTask.deleteFile(selectedFile)).toURI().toURL().toString()); } catch (IOException e) { statusView.setText(e.getMessage()); Log.d("deleteFile", e.getMessage(), e); } } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?deleteGroup="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String groupFile = urlStatus.substring(urlStatus.indexOf("?deleteGroup=") + 13, urlStatus.length()); int indexOf = groupFile.indexOf(","); final int group = Integer.parseInt(groupFile.substring(0, indexOf)); final String selectedFile = groupFile.substring(indexOf + 1); Log.d("groupFile", ",groupFile=" + groupFile + ", url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete Group of Files?"); alert.setMessage( "Do you really want to delete this group, except file \"" + selectedFile + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.postDelayed(new Runnable() { @Override public void run() { try { webView.loadUrl(new File(dupTask.deleteGroup(group, selectedFile)).toURI() .toURL().toString()); } catch (Throwable e) { statusView.setText(e.getMessage()); Log.e("Delete Group", e.getMessage(), e); Log.e("Delete Group", locX + ", " + locY + ", " + currentUrl); } } }, 0); } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?deleteFolder="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String selectedFile = urlStatus.substring(urlStatus.indexOf("?deleteFolder=") + 14, urlStatus.length()); Log.d("deleteFolder", ",deleteFolder=" + selectedFile + ", url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete folder?"); alert.setMessage("Do you really want to delete duplicate in folder \"" + selectedFile.substring(0, selectedFile.lastIndexOf("/")) + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.postDelayed(new Runnable() { @Override public void run() { try { webView.loadUrl(new File(dupTask.deleteFolder(selectedFile)).toURI().toURL() .toString()); } catch (Throwable e) { statusView.setText(e.getMessage()); Log.e("Delete folder", e.getMessage(), e); Log.e("Delete folder", locX + ", " + locY + ", " + currentUrl); } } }, 0); } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?deleteSub="); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } String urlStatus = Util.getUrlStatus(url); final String selectedFile = urlStatus.substring(urlStatus.indexOf("?deleteSub=") + 11, urlStatus.length()); Log.d("deleteSub", ",deleteSub=" + selectedFile + ", url=" + url + ", urlStatus=" + urlStatus); AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle("Delete sub folder?"); alert.setMessage("Do you really want to delete duplicate files in sub folder of \"" + selectedFile.substring(0, selectedFile.lastIndexOf("/")) + "\"?"); alert.setCancelable(true); alert.setNegativeButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { locX = webView.getScrollX(); locY = webView.getScrollY(); webView.postDelayed(new Runnable() { @Override public void run() { try { webView.loadUrl(new File(dupTask.deleteSubFolder(selectedFile)).toURI() .toURL().toString()); } catch (Throwable e) { statusView.setText(e.getMessage()); Log.e("Delete sub folder", e.getMessage(), e); Log.e("Delete sub folder", locX + ", " + locY + ", " + currentUrl); } } }, 0); } }); alert.setPositiveButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = alert.create(); alertDialog.show(); return true; } ind = url.indexOf("?viewName"); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } nameOrder = !nameOrder; locX = 0; locY = 0; Log.d("url=", url + ", viewName"); try { webView.loadUrl(new File(dupTask.genFile(dupTask.groupList, dupTask.NAME_VIEW)).toURI() .toURL().toString()); } catch (IOException e) { Log.e("viewName", e.getMessage(), e); } return true; } ind = url.indexOf("?viewGroup"); if (ind >= 0) { if (dupTask == null) { showToast("Please do duplicate finding again."); return true; } groupViewChanged = true; locX = 0; locY = 0; Log.d("url=", url + ", viewGroup"); try { webView.loadUrl(new File(dupTask.genFile(dupTask.groupList, dupTask.GROUP_VIEW)).toURI() .toURL().toString()); } catch (IOException e) { Log.e("viewGroup", e.getMessage(), e); } return true; } if (zextr == null) { locX = 0; locY = 0; } else { zextr = null; } if (MainActivity.popup) { final MainFragment frag = ((MainActivity) activity).addFragmentToStack(); frag.status = Util.getUrlStatus(url); frag.load = load; frag.currentSearching = currentSearching; frag.selectedFiles = selectedFiles; frag.files = files; frag.currentZipFileName = currentZipFileName; if (extractFile != null) { try { frag.extractFile = new ExtractFile(); extractFile.copyTo(frag.extractFile); } catch (RarException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } frag.home = home; // if (mSearchView != null && mSearchView.getQuery().length() > 0) { // frag.mSearchView.setQuery(mSearchView.getQuery(), false); // } view.getHandler().postDelayed(new Runnable() { @Override public void run() { frag.webTask = new WebTask(MainFragment.this); frag.webTask.init(frag.webView, url); frag.webTask.execute(); frag.statusView.setText(frag.status); } }, 100); } else { currentUrl = url; Log.d("currentUrl 19", currentUrl); status = Util.getUrlStatus(url); statusView.setText("Opening " + url + "..."); webTask = new WebTask(MainFragment.this, webView, url, status.toString()); webTask.execute(); } // setNavVisibility(false); return true; } // @Override // public WebResourceResponse shouldInterceptRequest(WebView view, String url) { // } @Override public void onPageFinished(WebView view, String url) { if (container != null) { if (showFind) { container.setVisibility(View.VISIBLE); webView.findAllAsync(findBox.getText().toString()); } else { container.setVisibility(View.INVISIBLE); } } Log.d("onPageFinished", locX + ", " + locY + ", currentUrl=" + currentUrl + ", url=" + url); setNavVisibility(false); if (!backForward) { //if (zextr != null) { // zextr = null; jumpTo(locX, locY); } else { backForward = false; } // locX = 0; // locY = 0; Log.d("onPageFinished", url); /* This call inject JavaScript into the page which just finished loading. */ // webView.loadUrl("javascript:window.HTMLOUT.processHTML(" + // "'<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');"); } }); WebSettings settings = webView.getSettings(); // webView.setWebViewClient(new WebViewClient()); // webView.setWebChromeClient(new WebChromeClient()); // webView.addJavascriptInterface(new HtmlSourceViewJavaScriptInterface(), "HTMLOUT"); settings.setMinimumFontSize(13); settings.setJavaScriptEnabled(true); settings.setDefaultTextEncodingName("UTF-8"); settings.setBuiltInZoomControls(true); // settings.setSansSerifFontFamily("Tahoma"); settings.setEnableSmoothTransition(true); return v; }
From source file:com.cw.litenote.note.Note_adapter.java
private void setWebView(final CustomWebView webView, Object object, int whichView) { final SharedPreferences pref_web_view = act.getSharedPreferences("web_view", 0); final ProgressBar spinner = (ProgressBar) ((View) object).findViewById(R.id.loading); if (whichView == CustomWebView.TEXT_VIEW) { int scale = pref_web_view.getInt("KEY_WEB_VIEW_SCALE", 0); webView.setInitialScale(scale);// w w w .j a v a 2s . co m } else if (whichView == CustomWebView.LINK_VIEW) { bWebViewIsShown = false; webView.setInitialScale(30); } int style = Note.getStyle(); webView.setBackgroundColor(ColorSet.mBG_ColorArray[style]); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setSupportZoom(true); webView.getSettings().setUseWideViewPort(true); // customWebView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setJavaScriptEnabled(true);//warning: Using setJavaScriptEnabled can introduce XSS vulnerabilities // // speed up // if (Build.VERSION.SDK_INT >= 19) { // // chromium, enable hardware acceleration // webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); // } else { // // older android version, disable hardware acceleration // webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // } if (whichView == CustomWebView.TEXT_VIEW) { webView.setWebViewClient(new WebViewClient() { @Override public void onScaleChanged(WebView web_view, float oldScale, float newScale) { super.onScaleChanged(web_view, oldScale, newScale); // System.out.println("Note_adapter / onScaleChanged"); // System.out.println(" oldScale = " + oldScale); // System.out.println(" newScale = " + newScale); int newDefaultScale = (int) (newScale * 100); pref_web_view.edit().putInt("KEY_WEB_VIEW_SCALE", newDefaultScale).apply(); //update current position NoteUi.setFocus_notePos(pager.getCurrentItem()); } @Override public void onPageFinished(WebView view, String url) { } }); } if (whichView == CustomWebView.LINK_VIEW) { webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { System.out.println("---------------- spinner progress = " + progress); if (spinner != null) { if (bWebViewIsShown) { if (progress < 100 && (spinner.getVisibility() == ProgressBar.GONE)) { webView.setVisibility(View.GONE); spinner.setVisibility(ProgressBar.VISIBLE); } spinner.setProgress(progress); if (progress > 30) bWebViewIsShown = true; } if (bWebViewIsShown || (progress == 100)) { spinner.setVisibility(ProgressBar.GONE); webView.setVisibility(View.VISIBLE); } } } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (!TextUtils.isEmpty(title) && !title.equalsIgnoreCase("about:blank")) { System.out.println("Note_adapter / _onReceivedTitle / title = " + title); int position = NoteUi.getFocus_notePos(); String tag = "current" + position + "textWebView"; CustomWebView textWebView = (CustomWebView) pager.findViewWithTag(tag); String strLink = db_page.getNoteLinkUri(position, true); // show title of http link if ((textWebView != null) && !Util.isYouTubeLink(strLink) && strLink.startsWith("http")) { mWebTitle = title; showTextWebView(position, textWebView); } } } }); } }
From source file:com.google.android.apps.paco.ExploreDataActivity.java
private WebViewClient createWebViewClientThatHandlesFileLinksForCharts() { WebViewClient webViewClient = new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url);//from w w w . j ava2 s. c om if (uri.getScheme().startsWith("http")) { return true; } view.loadUrl(FeedbackActivity.stripQuery(url)); return true; } }; return webViewClient; }
From source file:com.sonymobile.dronecontrol.activity.MainActivity.java
private void loadLicense() { View view = getLayoutInflater().inflate(R.layout.licenses, null); Dialog dialog = new AlertDialog.Builder(this).setPositiveButton(R.string.settings_button_ok, null) .setView(view).setTitle(getString(R.string.settings_item_licenses)).create(); final WebView webView = (WebView) view.findViewById(R.id.license_view); final ProgressBar webProgress = (ProgressBar) view.findViewById(R.id.license_progress); webProgress.setVisibility(View.VISIBLE); dialog.setOnDismissListener(new OnDismissListener() { @Override/*w ww .ja v a 2 s . c o m*/ public void onDismiss(DialogInterface dialog) { webView.stopLoading(); } }); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { super.onScaleChanged(view, oldScale, newScale); webProgress.setVisibility(View.GONE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); webProgress.setVisibility(View.GONE); } }); webView.loadUrl("file:///android_asset/licenses.html"); dialog.show(); }