List of usage examples for android.webkit WebChromeClient WebChromeClient
WebChromeClient
From source file:phonegap.plugins.childBrowser.ChildBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load. * @param jsonObject//from ww w . jav a 2 s .co m */ public String showWebPage(final String url, JSONObject options) { // Determine if we should hide the location bar. if (options != null) { showLocationBar = options.optBoolean("showLocationBar", true); } // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { try { JSONObject obj = new JSONObject(); obj.put("type", CLOSE_EVENT); sendUpdate(obj, false); } catch (JSONException e) { Log.d(LOG_TAG, "Should never happen"); } } }); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); try { back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); try { forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close button ImageButton close = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); try { close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView webview = new WebView(cordova.getActivity()); webview.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); webview.setWebChromeClient(new WebChromeClient()); WebViewClient client = new ChildBrowserClient(edittext); webview.setWebViewClient(client); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); settings.setPluginsEnabled(true); settings.setDomStorageEnabled(true); webview.loadUrl(url); webview.setId(6); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.requestFocus(); webview.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(webview); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.FILL_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); } private Bitmap loadDrawable(String filename) throws java.io.IOException { InputStream input = cordova.getActivity().getAssets().open(filename); return BitmapFactory.decodeStream(input); } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }
From source file:com.dhaval.mobile.plugin.ChildBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load. * @param jsonObject /* w w w. j a v a 2s . c o m*/ */ public String showWebPage(final String url, JSONObject options) { // Determine if we should hide the location bar. if (options != null) { showLocationBar = options.optBoolean("showLocationBar", true); showAddressBar = options.optBoolean("showAddressBar", true); } // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, ctx.getContext().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new Dialog(ctx.getContext(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { try { JSONObject obj = new JSONObject(); obj.put("type", CLOSE_EVENT); sendUpdate(obj, false); } catch (JSONException e) { Log.d(LOG_TAG, "Should never happen"); } } }); // Main container layout LinearLayout main = new LinearLayout(ctx.getContext()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(ctx.getContext()); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(ctx.getContext()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button ImageButton back = new ImageButton(ctx.getContext()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); try { back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(ctx.getContext()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); try { forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(ctx.getContext()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); if (!showAddressBar) { edittext.setVisibility(EditText.INVISIBLE); } // Close button ImageButton close = new ImageButton(ctx.getContext()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); try { close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView webview = new WebView(ctx.getContext()); webview.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); webview.setWebChromeClient(new WebChromeClient()); WebViewClient client = new ChildBrowserClient(edittext); webview.setWebViewClient(client); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); settings.setPluginsEnabled(true); settings.setDomStorageEnabled(true); webview.loadUrl(url); webview.setId(6); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.requestFocus(); webview.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(webview); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.FILL_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); } private Bitmap loadDrawable(String filename) throws java.io.IOException { InputStream input = ctx.getAssets().open(filename); return BitmapFactory.decodeStream(input); } }; this.ctx.runOnUiThread(runnable); return ""; }
From source file:rdx.andro.forexcapplugins.childBrowser.ChildBrowser.java
/** * Display a new browser with the specified URL. * /* w ww . java 2 s . co m*/ * @param url * The url to load. * @param jsonObject */ public String showWebPage(final String url, JSONObject options) { // Determine if we should hide the location bar. if (options != null) { showLocationBar = options.optBoolean("showLocationBar", true); } // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { try { JSONObject obj = new JSONObject(); obj.put("type", CLOSE_EVENT); sendUpdate(obj, false); } catch (JSONException e) { Log.d(LOG_TAG, "Should never happen"); } } }); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); try { back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); try { forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except // input... Makes // the text // NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" // button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close button ImageButton close = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); try { close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView webview = new WebView(cordova.getActivity()); webview.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); webview.setWebChromeClient(new WebChromeClient()); WebViewClient client = new ChildBrowserClient(edittext); webview.setWebViewClient(client); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); // settings.setPluginState(true); settings.setDomStorageEnabled(true); webview.loadUrl(url); webview.setId(6); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.requestFocus(); webview.requestFocusFromTouch(); // Add the back and forward buttons to our action button // container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(webview); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.FILL_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); } private Bitmap loadDrawable(String filename) throws java.io.IOException { InputStream input = cordova.getActivity().getAssets().open(filename); return BitmapFactory.decodeStream(input); } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }
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// www .j ava2 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.chatwingsdk.activities.CommunicationActivity.java
@SuppressLint("SetJavaScriptEnabled") @Override//from w w w. ja v a 2 s .co m public void ensureWebViewAndSubscribeToChannels() { if (mCurrentCommunicationMode == null) return; // Check whether the web view is available or not. // If not, init it and load faye client. When loading finished, // this method will be recursively called. At that point, // the actual subscribe code will be executed. if (mWebView == null) { mNotSubscribeToChannels = true; mWebView = new WebView(this); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME); mWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LogUtils.v(consoleMessage.message() + " -- level " + consoleMessage.messageLevel() + " -- From line " + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId()); //This workaround tries to fix issue webview is not subscribe successfully //when the screen is off, we cant listen for otto event since it's dead before that //this likely happens on development or very rare case in production if (consoleMessage.messageLevel().equals(ConsoleMessage.MessageLevel.ERROR)) { mWebView = null; mNotSubscribeToChannels = true; } return true; } }); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (url.equals(Constants.FAYE_CLIENT_URL)) { // Recursively call this method, // to execute subscribe code. ensureWebViewAndSubscribeToChannels(); } } }); mWebView.loadUrl(Constants.FAYE_CLIENT_URL); return; } if (mNotSubscribeToChannels) { mNotSubscribeToChannels = false; mCurrentCommunicationMode.subscribeToChannels(mWebView); } }
From source file:com.cloudexplorers.plugins.childBrowser.ChildBrowser.java
/** * Display a new browser with the specified URL. * // w w w . j a v a2 s .co m * @param url * The url to load. * @param jsonObject */ public String showWebPage(final String url, JSONObject options) { // Determine if we should hide the location bar. if (options != null) { showLocationBar = options.optBoolean("showLocationBar", true); } // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, cordova.getActivity().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { try { JSONObject obj = new JSONObject(); obj.put("type", CLOSE_EVENT); sendUpdate(obj, false); } catch (JSONException e) { Log.d(LOG_TAG, "Should never happen"); } } }); // Main container layout LinearLayout main = new LinearLayout(cordova.getActivity()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(cordova.getActivity()); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button ImageButton back = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); try { back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); try { forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(cordova.getActivity()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... // Makes the text // NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); // Close button ImageButton close = new ImageButton(cordova.getActivity()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); try { close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView webview = new WebView(cordova.getActivity()); webview.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); webview.setWebChromeClient(new WebChromeClient()); WebViewClient client = new ChildBrowserClient(edittext); webview.setWebViewClient(client); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); settings.setPluginsEnabled(true); settings.setDomStorageEnabled(true); webview.loadUrl(url); webview.setId(6); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setPluginsEnabled(true); webview.requestFocus(); webview.requestFocusFromTouch(); // Add the back and forward buttons to our action button container // layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(webview); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.FILL_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); } private Bitmap loadDrawable(String filename) throws java.io.IOException { InputStream input = cordova.getActivity().getAssets().open(filename); return BitmapFactory.decodeStream(input); } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }
From source file:com.facebook.react.views.webview.ReactWebViewManager.java
@Override protected WebView createViewInstance(final ThemedReactContext reactContext) { final ReactWebView webView = new ReactWebView(reactContext); /**/* w ww . j a va 2 s. c o m*/ * cookie? * 5.0???cookie,5.0?false * */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true); } webView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); reactContext.getCurrentActivity().startActivity(intent); // DownloadManager.Request request = new DownloadManager.Request( // Uri.parse(url)); // // request.setMimeType(mimetype); // String cookies = CookieManager.getInstance().getCookie(url); // request.addRequestHeader("cookie", cookies); // request.addRequestHeader("User-Agent", userAgent); // request.allowScanningByMediaScanner(); //// request.setTitle() // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed! // request.setDestinationInExternalPublicDir( // Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName( // url, contentDisposition, mimetype)); // DownloadManager dm = (DownloadManager) reactContext.getCurrentActivity().getSystemService(DOWNLOAD_SERVICE); // dm.enqueue(request); // Toast.makeText(reactContext, "...", //To notify the Client that the file is being downloaded // Toast.LENGTH_LONG).show(); } }); webView.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage message) { if (ReactBuildConfig.DEBUG) { return super.onConsoleMessage(message); } // Ignore console logs in non debug builds. return true; } @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File imageFile = new File(storageDir, /* directory */ imageFileName + ".jpg" /* filename */ ); return imageFile; } public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(null); } mFilePathCallback = filePathCallback; Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent .resolveActivity(reactContext.getCurrentActivity().getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); } catch (IOException ex) { // Error occurred while creating the File FLog.e(ReactConstants.TAG, "Unable to create Image File", ex); } // Continue only if the File was successfully created if (photoFile != null) { mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } else { takePictureIntent = null; } } Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("*/*"); Intent[] intentArray; if (takePictureIntent != null) { intentArray = new Intent[] { takePictureIntent }; } else { intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, "?"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); // final Intent galleryIntent = new Intent(Intent.ACTION_PICK); // galleryIntent.setType("image/*"); // final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choose File"); // reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); return true; } @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (mVideoView != null) { callback.onCustomViewHidden(); return; } // Store the view and it's callback for later, so we can dispose of them correctly mVideoView = view; mCustomViewCallback = callback; view.setBackgroundColor(Color.BLACK); getRootView().addView(view, FULLSCREEN_LAYOUT_PARAMS); webView.setVisibility(View.GONE); UiThreadUtil.runOnUiThread(new Runnable() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void run() { // If the status bar is translucent hook into the window insets calculations // and consume all the top insets so no padding will be added under the status bar. View decorView = reactContext.getCurrentActivity().getWindow().getDecorView(); decorView.setOnApplyWindowInsetsListener(null); ViewCompat.requestApplyInsets(decorView); } }); reactContext.getCurrentActivity() .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } @Override public void onHideCustomView() { if (mVideoView == null) { return; } mVideoView.setVisibility(View.GONE); getRootView().removeView(mVideoView); mVideoView = null; mCustomViewCallback.onCustomViewHidden(); webView.setVisibility(View.VISIBLE); // View decorView = reactContext.getCurrentActivity().getWindow().getDecorView(); // // Show Status Bar. // int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE; // decorView.setSystemUiVisibility(uiOptions); UiThreadUtil.runOnUiThread(new Runnable() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void run() { // If the status bar is translucent hook into the window insets calculations // and consume all the top insets so no padding will be added under the status bar. View decorView = reactContext.getCurrentActivity().getWindow().getDecorView(); // decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { // @Override // public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) { // WindowInsets defaultInsets = v.onApplyWindowInsets(insets); // return defaultInsets.replaceSystemWindowInsets( // defaultInsets.getSystemWindowInsetLeft(), // 0, // defaultInsets.getSystemWindowInsetRight(), // defaultInsets.getSystemWindowInsetBottom()); // } // }); decorView.setOnApplyWindowInsetsListener(null); ViewCompat.requestApplyInsets(decorView); } }); reactContext.getCurrentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } private ViewGroup getRootView() { return ((ViewGroup) reactContext.getCurrentActivity().findViewById(android.R.id.content)); } }); reactContext.addLifecycleEventListener(webView); reactContext.addActivityEventListener(new ActivityEventListener() { @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) { return; } Uri[] results = null; // Check that the response is a good one if (resultCode == Activity.RESULT_OK) { if (data == null) { // If there is not data, then we may have taken a photo if (mCameraPhotoPath != null) { results = new Uri[] { Uri.parse(mCameraPhotoPath) }; } } else { String dataString = data.getDataString(); if (dataString != null) { results = new Uri[] { Uri.parse(dataString) }; } } } if (results == null) { mFilePathCallback.onReceiveValue(new Uri[] {}); } else { mFilePathCallback.onReceiveValue(results); } mFilePathCallback = null; return; } @Override public void onNewIntent(Intent intent) { } }); mWebViewConfig.configWebView(webView); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setDisplayZoomControls(false); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setDefaultFontSize(16); webView.getSettings().setTextZoom(100); // Fixes broken full-screen modals/galleries due to body height being 0. webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } return webView; }
From source file:com.ibuildapp.romanblack.CataloguePlugin.ProductDetails.java
/** * Initializing user interface/*from ww w. ja v a 2s.com*/ */ 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.android.mail.ui.ConversationViewFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.conversation_view, container, false); mConversationContainer = (ConversationContainer) rootView.findViewById(R.id.conversation_container); mConversationContainer.setAccountController(this); mTopmostOverlay = (ViewGroup) mConversationContainer.findViewById(R.id.conversation_topmost_overlay); mTopmostOverlay.setOnKeyListener(this); inflateSnapHeader(mTopmostOverlay, inflater); mConversationContainer.setupSnapHeader(); setupNewMessageBar();/* w w w . ja v a2s . c o m*/ mProgressController = new ConversationViewProgressController(this, getHandler()); mProgressController.instantiateProgressIndicators(rootView); mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.conversation_webview); mWebView.addJavascriptInterface(mJsBridge, "mail"); // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete // Below JB, try to speed up initial render by having the webview do supplemental draws to // custom a software canvas. // TODO(mindyp): //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op // animation that immediately runs on page load. The app uses this as a signal that the // content is loaded and ready to draw, since WebView delays firing this event until the // layers are composited and everything is ready to draw. // This signal does not seem to be reliable, so just use the old method for now. final boolean isJBOrLater = Utils.isRunningJellybeanOrLater(); final boolean isUserVisible = isUserVisible(); mWebView.setUseSoftwareLayer(!isJBOrLater); mEnableContentReadySignal = isJBOrLater && isUserVisible; mWebView.onUserVisibilityChanged(isUserVisible); mWebView.setWebViewClient(mWebViewClient); final WebChromeClient wcc = new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { if (consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR) { LogUtils.e(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(), consoleMessage.lineNumber(), ConversationViewFragment.this); } else { LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(), consoleMessage.lineNumber(), ConversationViewFragment.this); } return true; } }; mWebView.setWebChromeClient(wcc); final WebSettings settings = mWebView.getSettings(); final ScrollIndicatorsView scrollIndicators = (ScrollIndicatorsView) rootView .findViewById(R.id.scroll_indicators); scrollIndicators.setSourceView(mWebView); settings.setJavaScriptEnabled(true); ConversationViewUtils.setTextZoom(getResources(), settings); if (Utils.isRunningLOrLater()) { CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true /* accept */); } mViewsCreated = true; mWebViewLoadedData = false; return rootView; }
From source file:com.google.android.apps.paco.ExploreDataActivity.java
private void setWebChromeClientThatHandlesAlertsAsDialogs() { webView.setWebChromeClient(new WebChromeClient() { @Override/*from w w w . java 2 s.c om*/ public boolean onJsAlert(WebView view, String url, String message, JsResult result) { new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true) .setPositiveButton(R.string.ok, new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); result.confirm(); return true; } public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { if (url.contains("file:///android_asset/map.html")) { if (showDialog == false) { result.confirm(); return true; } else { new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true) .setPositiveButton(R.string.ok, new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { showDialog = false; dialog.dismiss(); result.confirm(); } }).setNegativeButton(R.string.cancel_button, new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); result.cancel(); } }).create().show(); return true; } } return super.onJsConfirm(view, url, message, result); } }); }