List of usage examples for android.webkit WebChromeClient WebChromeClient
WebChromeClient
From source file:com.phonegap.plugins.childBrowser.ChildBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load./*from w w w . j av a 2s . c o m*/ * @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() { public void run() { dialog = new Dialog(ctx.getContext()); 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"); } } }); LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f); LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); LinearLayout main = new LinearLayout(ctx.getContext()); main.setOrientation(LinearLayout.VERTICAL); LinearLayout toolbar = new LinearLayout(ctx.getContext()); toolbar.setOrientation(LinearLayout.HORIZONTAL); ImageButton back = new ImageButton(ctx.getContext()); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); back.setId(1); try { back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } back.setLayoutParams(backParams); ImageButton forward = new ImageButton(ctx.getContext()); forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); forward.setId(2); try { forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } forward.setLayoutParams(forwardParams); edittext = new EditText(ctx.getContext()); 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; } }); edittext.setId(3); edittext.setSingleLine(true); edittext.setText(url); edittext.setLayoutParams(editParams); ImageButton close = new ImageButton((Context) ctx); close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); close.setId(4); try { close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } close.setLayoutParams(closeParams); webview = new WebView(ctx.getContext()); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setBuiltInZoomControls(true); // dda: intercept calls to console.log webview.setWebChromeClient(new WebChromeClient() { public boolean onConsoleMessage(ConsoleMessage cmsg) { // check secret prefix if (cmsg.message().startsWith("MAGIC")) { String msg = cmsg.message().substring(5); // strip off prefix /* process HTML */ try { JSONObject obj = new JSONObject(); obj.put("type", PAGE_LOADED); obj.put("html", msg); sendUpdate(obj, true); } catch (JSONException e) { Log.d("ChildBrowser", "This should never happen"); } return true; } return false; } }); // dda: inject the JavaScript on page load webview.setWebViewClient(new ChildBrowserClient(edittext) { public void onPageFinished(WebView view, String address) { // have the page spill its guts, with a secret prefix Log.d("ChildBrowser", "\n\nInjecting javascript\n\n"); view.loadUrl( "javascript:console.log('MAGIC'+document.getElementsByTagName('html')[0].innerHTML);"); } }); // webview.setWebViewClient(client); webview.loadUrl(url); webview.setId(5); webview.setInitialScale(0); webview.setLayoutParams(wvParams); webview.requestFocus(); webview.requestFocusFromTouch(); toolbar.addView(back); toolbar.addView(forward); toolbar.addView(edittext); toolbar.addView(close); if (getShowLocationBar()) { main.addView(toolbar); } 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:com.pursuer.reader.easyrss.VerticalSingleItemView.java
@SuppressLint({ "NewApi", "SimpleDateFormat" }) public VerticalSingleItemView(final DataMgr dataMgr, final Context context, final String uid, final View menu, final VerticalItemViewCtrl itemViewCtrl) { this.dataMgr = dataMgr; this.context = context; this.item = dataMgr.getItemByUid(uid, ITEM_PROJECTION); this.fontSize = new SettingFontSize(dataMgr).getData(); this.theme = new SettingTheme(dataMgr).getData(); this.showTop = false; this.showBottom = false; this.menu = menu; this.itemViewCtrl = itemViewCtrl; this.imageClickTime = 0; final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.view = inflater.inflate(R.layout.single_item_view, null); // Disable hardware acceleration on Android 3.0-4.1 devices. if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { view.setLayerType(View.LAYER_TYPE_SOFTWARE, null); }//w w w . j a v a 2 s . c o m lastItemView = view.findViewById(R.id.LastItemView); nextItemView = view.findViewById(R.id.NextItemView); itemScrollView = (OverScrollView) view.findViewById(R.id.ItemScrollView); itemScrollView.setTopScrollView(lastItemView); itemScrollView.setBottomScrollView(nextItemView); itemScrollView.setOnScrollChangeListener(this); itemScrollView.setOnTouchListener(this); final View btnShowOriginal = view.findViewById(R.id.BtnShowOriginal); btnShowOriginal.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(final View view, final MotionEvent event) { boolean ret = false; final TextView txt = (TextView) view.findViewById(R.id.BtnText); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: txt.setTextColor(0xFF787878); ret = true; break; case MotionEvent.ACTION_MOVE: ret = true; break; case MotionEvent.ACTION_CANCEL: txt.setTextColor(0xBB787878); ret = false; break; case MotionEvent.ACTION_UP: txt.setTextColor(0xBB787878); final SettingBrowserChoice setting = new SettingBrowserChoice(dataMgr); if (setting.getData() == SettingBrowserChoice.BROWSER_CHOICE_EXTERNAL) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse(item.getHref())); context.startActivity(intent); } else if (VerticalSingleItemView.this.listener != null) { VerticalSingleItemView.this.listener.showWebsitePage(item.getUid(), false); } break; default: } return ret; } }); final View btnShowMobilized = view.findViewById(R.id.BtnShowMobilized); btnShowMobilized.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(final View view, final MotionEvent event) { boolean ret = false; final TextView txt = (TextView) view.findViewById(R.id.BtnText); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: txt.setTextColor(0xFF787878); ret = true; break; case MotionEvent.ACTION_MOVE: ret = true; break; case MotionEvent.ACTION_CANCEL: txt.setTextColor(0xBB787878); ret = false; break; case MotionEvent.ACTION_UP: txt.setTextColor(0xBB787878); if (VerticalSingleItemView.this.listener != null) { VerticalSingleItemView.this.listener.showWebsitePage(item.getUid(), true); } ret = true; break; default: } return ret; } }); { final ListItemItem lastItem = itemViewCtrl.getLastItem(item.getUid()); final TextView txt = (TextView) lastItemView.findViewById(R.id.LastItemTitle); txt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize); if (lastItem == null) { lastUid = null; menu.findViewById(R.id.BtnPrevious).setEnabled(false); final ImageView img = (ImageView) lastItemView.findViewById(R.id.LastItemArrow); img.setImageResource(R.drawable.no_more_circle); txt.setText(R.string.TxtNoPreviousItem); } else { lastUid = lastItem.getId(); final View btnLast = menu.findViewById(R.id.BtnPrevious); btnLast.setEnabled(true); btnLast.setOnClickListener(new OnClickListener() { @Override public void onClick(final View view) { if (listener != null) { listener.showLastItem(); } } }); txt.setText(lastItem.getTitle()); } } { final ListItemItem nextItem = itemViewCtrl.getNextItem(item.getUid()); final TextView txt = (TextView) nextItemView.findViewById(R.id.NextItemTitle); txt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize); if (nextItem == null) { nextUid = null; menu.findViewById(R.id.BtnNext).setEnabled(false); final ImageView img = (ImageView) nextItemView.findViewById(R.id.NextItemArrow); img.setImageResource(R.drawable.no_more_circle); txt.setText(R.string.TxtNoNextItem); } else { nextUid = nextItem.getId(); final View btnNext = menu.findViewById(R.id.BtnNext); btnNext.setEnabled(true); btnNext.setOnClickListener(new OnClickListener() { @Override public void onClick(final View view) { if (listener != null) { listener.showNextItem(); } } }); txt.setText(nextItem.getTitle()); } } final TextView title = (TextView) view.findViewById(R.id.ItemTitle); title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 3); title.setText(item.getTitle()); final TextView info = (TextView) view.findViewById(R.id.ItemInfo); info.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 5); final StringBuilder infoText = new StringBuilder(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); sdf.setTimeZone(TimeZone.getDefault()); infoText.append(sdf.format(Utils.timestampToDate(item.getTimestamp()))); if (item.getAuthor() != null && item.getAuthor().length() > 0) { infoText.append(" | By "); infoText.append(item.getAuthor()); } if (item.getSourceTitle() != null && item.getSourceTitle().length() > 0) { infoText.append(" ("); infoText.append(item.getSourceTitle()); infoText.append(")"); } info.setText(infoText); webView = (WebView) view.findViewById(R.id.webView); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setBackgroundColor(context.getResources() .getColor(theme == SettingTheme.THEME_NORMAL ? R.color.NormalBackground : R.color.DarkBackground)); webView.setFocusable(false); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) { if (VerticalSingleItemView.this.imageClickTime > System.currentTimeMillis() - 1000) { return true; } final Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse(url)); context.startActivity(intent); return true; } }); webView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(final WebView view, final String url, final String message, final JsResult result) { if (VerticalSingleItemView.this.listener != null) { if (message.endsWith(".erss")) { VerticalSingleItemView.this.listener .onImageViewRequired(item.getStoragePath() + "/" + message); } else { VerticalSingleItemView.this.listener.onImageViewRequired(message); } } VerticalSingleItemView.this.imageClickTime = System.currentTimeMillis(); result.cancel(); return true; } }); updateButtonStar(); updateButtonSharing(); updateButtonOpenLink(); if (!item.getState().isRead()) { dataMgr.markItemAsReadWithTransactionByUid(uid); NetworkMgr.getInstance().startImmediateItemStateSyncing(); } }
From source file:mgks.os.webview.MainActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" }) @Override// w w w. ja v a2 s.co m protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.w("READ_PERM = ", Manifest.permission.READ_EXTERNAL_STORAGE); Log.w("WRITE_PERM = ", Manifest.permission.WRITE_EXTERNAL_STORAGE); //Prevent the app from being started again when it is still alive in the background if (!isTaskRoot()) { finish(); return; } setContentView(R.layout.activity_main); asw_view = findViewById(R.id.msw_view); final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh); if (ASWP_PULLFRESH) { pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { pull_fresh(); pullfresh.setRefreshing(false); } }); asw_view.getViewTreeObserver() .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (asw_view.getScrollY() == 0) { pullfresh.setEnabled(true); } else { pullfresh.setEnabled(false); } } }); } else { pullfresh.setRefreshing(false); pullfresh.setEnabled(false); } if (ASWP_PBAR) { asw_progress = findViewById(R.id.msw_progress); } else { findViewById(R.id.msw_progress).setVisibility(View.GONE); } asw_loading_text = findViewById(R.id.msw_loading_text); Handler handler = new Handler(); //Launching app rating request if (ASWP_RATINGS) { handler.postDelayed(new Runnable() { public void run() { get_rating(); } }, 1000 * 60); //running request after few moments } //Getting basic device information get_info(); //Getting GPS location of device if given permission if (ASWP_LOCATION && !check_permission(1)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } get_location(); //Webview settings; defaults are customized for best performance WebSettings webSettings = asw_view.getSettings(); if (!ASWP_OFFLINE) { webSettings.setJavaScriptEnabled(ASWP_JSCRIPT); } webSettings.setSaveFormData(ASWP_SFORM); webSettings.setSupportZoom(ASWP_ZOOM); webSettings.setGeolocationEnabled(ASWP_LOCATION); webSettings.setAllowFileAccess(true); webSettings.setAllowFileAccessFromFileURLs(true); webSettings.setAllowUniversalAccessFromFileURLs(true); webSettings.setUseWideViewPort(true); webSettings.setDomStorageEnabled(true); asw_view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); asw_view.setHapticFeedbackEnabled(false); asw_view.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) { if (!check_permission(2)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, file_perm); } else { 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.setDescription(getString(R.string.dl_downloading)); request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType)); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); assert dm != null; dm.enqueue(request); Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG) .show(); } } }); if (Build.VERSION.SDK_INT >= 21) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } else if (Build.VERSION.SDK_INT >= 19) { asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); } asw_view.setVerticalScrollBarEnabled(false); asw_view.setWebViewClient(new Callback()); //Rendering the default URL aswm_view(ASWV_URL, false); asw_view.setWebChromeClient(new WebChromeClient() { //Handling input[type="file"] requests for android API 16+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { if (ASWP_FUPLOAD) { asw_file_message = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req); } } //Handling input[type="file"] requests for android API 21+ public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (check_permission(2) && check_permission(3)) { if (ASWP_FUPLOAD) { if (asw_file_path != null) { asw_file_path.onReceiveValue(null); } asw_file_path = filePathCallback; Intent takePictureIntent = null; if (ASWP_CAMUPLOAD) { takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) { File photoFile = null; try { photoFile = create_image(); takePictureIntent.putExtra("PhotoPath", asw_cam_message); } catch (IOException ex) { Log.e(TAG, "Image file creation failed", ex); } if (photoFile != null) { asw_cam_message = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } else { takePictureIntent = null; } } } Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); if (!ASWP_ONLYCAM) { contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } } 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, getString(R.string.fl_chooser)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, asw_file_req); } return true; } else { get_file(); return false; } } //Getting webview rendering progress @Override public void onProgressChanged(WebView view, int p) { if (ASWP_PBAR) { asw_progress.setProgress(p); if (p == 100) { asw_progress.setProgress(0); } } } // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { if (Build.VERSION.SDK_INT < 23 || check_permission(1)) { // location permissions were granted previously so auto-approve callback.invoke(origin, true, false); } else { // location permissions not granted so request them ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } } }); if (getIntent().getData() != null) { String path = getIntent().getDataString(); /* If you want to check or use specific directories or schemes or hosts Uri data = getIntent().getData(); String scheme = data.getScheme(); String host = data.getHost(); List<String> pr = data.getPathSegments(); String param1 = pr.get(0); */ aswm_view(path, false); } }
From source file:com.baidu.cafe.local.record.WebElementRecorder.java
public void setHookedWebChromeClient(final WebView webView) { webElementEventCreator.prepareForStart(); if (webView != null) { webView.post(new Runnable() { public void run() { webView.getSettings().setJavaScriptEnabled(true); final WebChromeClient originalWebChromeClient = getOriginalWebChromeClient(webView); if (originalWebChromeClient != null) { webView.setWebChromeClient(new WebChromeClient() { HashMap<String, Boolean> invoke = new HashMap<String, Boolean>(); /** * Overrides onJsPrompt in order to create * {@code WebElement} objects based on the web * elements attributes prompted by the injections of * JavaScript/*from ww w . j a v a 2 s .c om*/ */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult r) { if (message != null) { if (message.endsWith("WebElementRecorder-finished")) { // Log.i("onJsPrompt : " + message); webElementEventCreator.setFinished(true); } else { webElementEventCreator.createWebElementEvent(message, view); } } r.confirm(); return true; } @Override public Bitmap getDefaultVideoPoster() { Bitmap ret = null; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.getDefaultVideoPoster(); invoke.put(funcName, false); } return ret; } @Override public View getVideoLoadingProgressView() { View ret = null; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.getVideoLoadingProgressView(); invoke.put(funcName, false); } return ret; } @Override public void getVisitedHistory(ValueCallback<String[]> callback) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.getVisitedHistory(callback); invoke.put(funcName, false); } } @Override public void onCloseWindow(WebView window) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onCloseWindow(window); invoke.put(funcName, false); } } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { boolean ret = false; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.onConsoleMessage(consoleMessage); invoke.put(funcName, false); } return ret; } @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onConsoleMessage(message, lineNumber, sourceID); invoke.put(funcName, false); } } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { boolean ret = false; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg); invoke.put(funcName, false); } return ret; } @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); invoke.put(funcName, false); } } @Override public void onGeolocationPermissionsHidePrompt() { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onGeolocationPermissionsHidePrompt(); invoke.put(funcName, false); } } @Override public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback); invoke.put(funcName, false); } } @Override public void onHideCustomView() { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onHideCustomView(); invoke.put(funcName, false); } } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { boolean ret = false; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.onJsAlert(view, url, message, result); invoke.put(funcName, false); } return ret; } @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { boolean ret = false; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.onJsBeforeUnload(view, url, message, result); invoke.put(funcName, false); } return ret; } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { boolean ret = false; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.onJsConfirm(view, url, message, result); invoke.put(funcName, false); } return ret; } @Override public boolean onJsTimeout() { boolean ret = false; String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); ret = originalWebChromeClient.onJsTimeout(); invoke.put(funcName, false); } return ret; } @Override public void onProgressChanged(WebView view, int newProgress) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onProgressChanged(view, newProgress); invoke.put(funcName, false); } } @Override public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); invoke.put(funcName, false); } } @Override public void onReceivedIcon(WebView view, Bitmap icon) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onReceivedIcon(view, icon); invoke.put(funcName, false); } } @Override public void onReceivedTitle(WebView view, String title) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onReceivedTitle(view, title); invoke.put(funcName, false); } } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed); invoke.put(funcName, false); } } @Override public void onRequestFocus(WebView view) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onRequestFocus(view); invoke.put(funcName, false); } } @Override public void onShowCustomView(View view, CustomViewCallback callback) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onShowCustomView(view, callback); invoke.put(funcName, false); } } public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { if (Build.VERSION.SDK_INT >= 14) { String funcName = new Throwable().getStackTrace()[1].getMethodName(); if (invoke.get(funcName) == null || !invoke.get(funcName)) { invoke.put(funcName, true); originalWebChromeClient.onShowCustomView(view, requestedOrientation, callback); invoke.put(funcName, false); } } } }); } else { webView.setWebChromeClient(new WebChromeClient() { /* (non-Javadoc) * @see android.webkit.WebChromeClient#getDefaultVideoPoster() */ @Override public Bitmap getDefaultVideoPoster() { // TODO Auto-generated method stub return super.getDefaultVideoPoster(); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#getVideoLoadingProgressView() */ @Override public View getVideoLoadingProgressView() { // TODO Auto-generated method stub return super.getVideoLoadingProgressView(); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#getVisitedHistory(android.webkit.ValueCallback) */ @Override public void getVisitedHistory(ValueCallback<String[]> callback) { // TODO Auto-generated method stub super.getVisitedHistory(callback); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onCloseWindow(android.webkit.WebView) */ @Override public void onCloseWindow(WebView window) { // TODO Auto-generated method stub super.onCloseWindow(window); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage) */ @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { // TODO Auto-generated method stub return super.onConsoleMessage(consoleMessage); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onConsoleMessage(java.lang.String, int, java.lang.String) */ @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { // TODO Auto-generated method stub super.onConsoleMessage(message, lineNumber, sourceID); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onCreateWindow(android.webkit.WebView, boolean, boolean, android.os.Message) */ @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { // TODO Auto-generated method stub return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onExceededDatabaseQuota(java.lang.String, java.lang.String, long, long, long, android.webkit.WebStorage.QuotaUpdater) */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { // TODO Auto-generated method stub super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onGeolocationPermissionsHidePrompt() */ @Override public void onGeolocationPermissionsHidePrompt() { // TODO Auto-generated method stub super.onGeolocationPermissionsHidePrompt(); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String, android.webkit.GeolocationPermissions.Callback) */ @Override public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { // TODO Auto-generated method stub super.onGeolocationPermissionsShowPrompt(origin, callback); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onHideCustomView() */ @Override public void onHideCustomView() { // TODO Auto-generated method stub super.onHideCustomView(); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onJsAlert(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult) */ @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { // TODO Auto-generated method stub return super.onJsAlert(view, url, message, result); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onJsBeforeUnload(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult) */ @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { // TODO Auto-generated method stub return super.onJsBeforeUnload(view, url, message, result); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onJsConfirm(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult) */ @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { // TODO Auto-generated method stub return super.onJsConfirm(view, url, message, result); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onJsPrompt(android.webkit.WebView, java.lang.String, java.lang.String, java.lang.String, android.webkit.JsPromptResult) */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { if (message != null) { if (message.endsWith("WebElementRecorder-finished")) { // Log.i("onJsPrompt : " + message); webElementEventCreator.setFinished(true); } else { webElementEventCreator.createWebElementEvent(message, view); } } result.confirm(); return true; } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onJsTimeout() */ @Override public boolean onJsTimeout() { // TODO Auto-generated method stub return super.onJsTimeout(); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onProgressChanged(android.webkit.WebView, int) */ @Override public void onProgressChanged(WebView view, int newProgress) { // TODO Auto-generated method stub super.onProgressChanged(view, newProgress); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onReachedMaxAppCacheSize(long, long, android.webkit.WebStorage.QuotaUpdater) */ @Override public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) { // TODO Auto-generated method stub super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onReceivedIcon(android.webkit.WebView, android.graphics.Bitmap) */ @Override public void onReceivedIcon(WebView view, Bitmap icon) { // TODO Auto-generated method stub super.onReceivedIcon(view, icon); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onReceivedTitle(android.webkit.WebView, java.lang.String) */ @Override public void onReceivedTitle(WebView view, String title) { // TODO Auto-generated method stub super.onReceivedTitle(view, title); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onReceivedTouchIconUrl(android.webkit.WebView, java.lang.String, boolean) */ @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { // TODO Auto-generated method stub super.onReceivedTouchIconUrl(view, url, precomposed); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onRequestFocus(android.webkit.WebView) */ @Override public void onRequestFocus(WebView view) { // TODO Auto-generated method stub super.onRequestFocus(view); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onShowCustomView(android.view.View, android.webkit.WebChromeClient.CustomViewCallback) */ @Override public void onShowCustomView(View view, CustomViewCallback callback) { // TODO Auto-generated method stub super.onShowCustomView(view, callback); } /* (non-Javadoc) * @see android.webkit.WebChromeClient#onShowCustomView(android.view.View, int, android.webkit.WebChromeClient.CustomViewCallback) */ @Override public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { // TODO Auto-generated method stub super.onShowCustomView(view, requestedOrientation, callback); } }); } } }); } }
From source file:com.kaltura.playersdk.PlayerViewController.java
/** * Build player URL and load it to player view * param iFrameUrl- String url//w ww . ja v a 2s .c om */ public void setComponents(String iframeUrl) { if (mWebView == null) { mWebView = new KControlsView(getContext()); mWebView.setWebChromeClient(new WebChromeClient()); mWebView.setWebViewClient(new WebViewClient()); mWebView.clearCache(true); mWebView.clearHistory(); mWebView.getSettings().setJavaScriptEnabled(true); //mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); mWebView.setKControlsViewClient(this); mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); mWebView.setBackgroundColor(0); mCurSec = 0; ViewGroup.LayoutParams currLP = getLayoutParams(); LayoutParams wvLp = new LayoutParams(currLP.width, currLP.height); this.playerController = new KPlayerController(new KPlayer(mActivity), this); this.playerController.addPlayerToController(this); this.addView(mWebView, wvLp); } iframeUrl = RequestHandler.getIframeUrlWithNativeVersion(iframeUrl, this.getContext()); if (mIframeUrl == null || !mIframeUrl.equals(iframeUrl)) { iframeUrl = iframeUrl + "&iframeembed=true"; mIframeUrl = iframeUrl; mWebView.loadUrl(iframeUrl); } }
From source file:im.ene.lab.attiq.ui.activities.ItemDetailActivity.java
private void trySetupContentView() { mContentView.setVerticalScrollBarEnabled(false); mContentView.setHorizontalScrollBarEnabled(false); mContentView.getSettings().setJavaScriptEnabled(true); mContentView.setWebChromeClient(new WebChromeClient() { @Override//from w ww . j av a2 s . c o m public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); Log.d(TAG, "newProgress = [" + newProgress + "]"); } }); mContentView.addJavascriptInterface(this, "Attiq"); mContentView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } else { return false; } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); if (!mIsFirstTimeLoaded && mLoadingView != null) { mLoadingView.setAlpha(1.f); mLoadingView.setVisibility(View.VISIBLE); } } @Override public void onPageFinished(final WebView view, String url) { super.onPageFinished(view, url); if (PrefUtil.isMathJaxEnabled()) { view.evaluateJavascript("javascript:document.getElementById('content').innerHTML='" + doubleEscapeTeX(mArticle.getRenderedBody()) + "';", null); view.evaluateJavascript("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { view.loadUrl("javascript:(function () " + "{document.getElementsByTagName('body')[0].style.marginBottom = '0'})()"); } }); } mIsFirstTimeLoaded = true; if (mLoadingView != null) { ViewCompat.animate(mLoadingView).alpha(0.f).setDuration(300) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationEnd(View view) { if (mLoadingView != null) { mLoadingView.setVisibility(View.GONE); } } }).start(); } } }); mContentView.setFindListener(new WebView.FindListener() { @Override public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) { if (mMenuLayout != null) { mMenuLayout.closeDrawer(GravityCompat.END); } if (numberOfMatches > 0 && mMenuAnchor != null && mContentView != null) { // FIXME Doesn't work now, because WebView is staying inside ScrollView mContentView.loadUrl("javascript:scrollToElement(\"" + mMenuAnchor.text() + "\");"); } } }); }
From source file:com.muzima.view.forms.FormWebViewActivity.java
private WebChromeClient createWebChromeClient() { return new WebChromeClient() { @Override/*w w w.j a va2 s . c om*/ public void onProgressChanged(WebView view, int progress) { FormWebViewActivity.this.setProgress(progress * 1000); if (progress == 100) { progressDialog.dismiss(); } } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { String message = format("Javascript Log. Message: {0}, lineNumber: {1}, sourceId, {2}", consoleMessage.message(), consoleMessage.lineNumber(), consoleMessage.sourceId()); if (consoleMessage.messageLevel() == ERROR) { Log.e(TAG, message); } else { Log.d(TAG, message); } return true; } }; }
From source file:mobi.monaca.framework.plugin.ChildBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load. * @param jsonObject// ww w .jav a 2s . 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); back.setImageResource(R.drawable.childbroswer_icon_arrow_left); 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); forward.setImageResource(R.drawable.childbroswer_icon_arrow_right); 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); close.setImageResource(R.drawable.childbroswer_icon_close); 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 { //TODO check LocalFileBootloader InputStream input = cordova.getActivity().getAssets().open(filename); return BitmapFactory.decodeStream(input); } }; this.cordova.getActivity().runOnUiThread(runnable); return ""; }
From source file:net.bluecarrot.lite.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setup the sharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // if the app is being launched for the first time if (savedPreferences.getBoolean("first_run", true)) { //todo presentation // save the fact that the app has been started at least once savedPreferences.edit().putBoolean("first_run", false).apply(); }/*from w ww.j a va 2 s. com*/ setContentView(R.layout.activity_main);//load the layout //**MOBFOX***// banner = (Banner) findViewById(R.id.banner); final Activity self = this; banner.setListener(new BannerListener() { @Override public void onBannerError(View view, Exception e) { //Toast.makeText(self, e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onBannerLoaded(View view) { //Toast.makeText(self, "banner loaded", Toast.LENGTH_SHORT).show(); } @Override public void onBannerClosed(View view) { //Toast.makeText(self, "banner closed", Toast.LENGTH_SHORT).show(); } @Override public void onBannerFinished(View view) { // Toast.makeText(self, "banner finished", Toast.LENGTH_SHORT).show(); } @Override public void onBannerClicked(View view) { //Toast.makeText(self, "banner clicked", Toast.LENGTH_SHORT).show(); } @Override public boolean onCustomEvent(JSONArray jsonArray) { return false; } }); banner.setInventoryHash(appHash); banner.load(); // setup the refresh layout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); swipeRefreshLayout.setColorSchemeResources(R.color.officialBlueFacebook, R.color.darkBlueSlimFacebookTheme);// set the colors swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshPage();//reload the page swipeRefresh = true; } }); /** get a subject and text and check if this is a link trying to be shared */ String sharedSubject = getIntent().getStringExtra(Intent.EXTRA_SUBJECT); String sharedUrl = getIntent().getStringExtra(Intent.EXTRA_TEXT); // if we have a valid URL that was shared by us, open the sharer if (sharedUrl != null) { if (!sharedUrl.equals("")) { // check if the URL being shared is a proper web URL if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) { // if it's not, let's see if it includes an URL in it (prefixed with a message) int startUrlIndex = sharedUrl.indexOf("http:"); if (startUrlIndex > 0) { // seems like it's prefixed with a message, let's trim the start and get the URL only sharedUrl = sharedUrl.substring(startUrlIndex); } } // final step, set the proper Sharer... urlSharer = String.format("https://m.facebook.com/sharer.php?u=%s&t=%s", sharedUrl, sharedSubject); // ... and parse it just in case urlSharer = Uri.parse(urlSharer).toString(); isSharer = true; } } // setup the webView webViewFacebook = (WebView) findViewById(R.id.webView); setUpWebViewDefaults(webViewFacebook); //fits images to screen if (isSharer) {//if is a share request webViewFacebook.loadUrl(urlSharer);//load the sharer url isSharer = false; } else goHome();//load homepage // webViewFacebook.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) { // public void onSwipeLeft() { // webViewFacebook.loadUrl("javascript:try{document.querySelector('#messages_jewel > a').click();}catch(e){window.location.href='" + // getString(R.string.urlFacebookMobile) + "messages/';}"); // } // // }); //WebViewClient that is the client callback. webViewFacebook.setWebViewClient(new WebViewClient() {//advanced set up // when there isn't a connetion public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { String summary = "<h1 style='text-align:center; padding-top:15%; font-size:70px;'>" + getString(R.string.titleNoConnection) + "</h1> <h3 " + "style='text-align:center; padding-top:1%; font-style: italic;font-size:50px;'>" + getString(R.string.descriptionNoConnection) + "</h3> <h5 style='font-size:30px; text-align:center; padding-top:80%; " + "opacity: 0.3;'>" + getString(R.string.awards) + "</h5>"; webViewFacebook.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page noConnectionError = true; swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing } // when I click in a external link public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url == null || Uri.parse(url).getHost().endsWith("facebook.com") || Uri.parse(url).getHost().endsWith("m.facebook.com") || url.contains(".gif")) { //url is ok return false; } else { if (Uri.parse(url).getHost().endsWith("fbcdn.net")) { //TODO add the possibility to download and share directly Toast.makeText(getApplicationContext(), getString(R.string.downloadOrShareWithBrowser), Toast.LENGTH_LONG).show(); //TODO get bitmap from url Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } //if the link doesn't contain 'facebook.com', open it using the browser startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } //https://www.facebook.com/dialog/return/close?#_=_ } //START management of loading @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { //TODO when I push on messages, open messanger // if(url!=null){ // if (url.contains("soft=messages") || url.contains("facebook.com/messages")) { // Toast.makeText(getApplicationContext(),"Open Messanger", // Toast.LENGTH_SHORT).show(); // startActivity(new Intent(getPackageManager().getLaunchIntentForPackage("com.facebook.orca")));//messanger // } // } // show you progress image if (!swipeRefresh) { if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh); refreshItem.setActionView(R.layout.circular_progress_bar); } } swipeRefresh = false; super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh); refreshItem.setActionView(null); } //load the css customizations String css = ""; if (savedPreferences.getBoolean("pref_blackTheme", false)) { css += getString(R.string.blackCss); } if (savedPreferences.getBoolean("pref_fixedBar", true)) { css += getString(R.string.fixedBar);//get the first part int navbar = 0;//default value int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//get id if (resourceId > 0) {//if there is navbar = getResources().getDimensionPixelSize(resourceId);//get the dimension } float density = getResources().getDisplayMetrics().density; int barHeight = (int) ((getResources().getDisplayMetrics().heightPixels - navbar - 44) / density); css += ".flyout { max-height:" + barHeight + "px; overflow-y:scroll; }";//without this doen-t scroll } if (savedPreferences.getBoolean("pref_hideSponsoredPosts", false)) { css += getString(R.string.hideSponsoredPost); } //apply the customizations webViewFacebook.loadUrl( "javascript:function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = " + "str; document.body.appendChild(node); } addStyleString('" + css + "');"); //finish the load super.onPageFinished(view, url); //when the page is loaded, stop the refreshing swipeRefreshLayout.setRefreshing(false); } //END management of loading }); //WebChromeClient for handling all chrome functions. webViewFacebook.setWebChromeClient(new WebChromeClient() { //to the Geolocation public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); //todo notify when the gps is used } //to upload files //!!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!! // for >= Lollipop, all in one public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { /** Request permission for external storage access. * If granted it's awesome and go on, * otherwise just stop here and leave the method. */ if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(null); } mFilePathCallback = filePathCallback; Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(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 Toast.makeText(getApplicationContext(), "Error occurred while creating the File", Toast.LENGTH_LONG).show(); } // 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("image/*"); 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, getString(R.string.chooseAnImage)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE); return true; } // creating image files (Lollipop only) private File createImageFile() throws IOException { String appDirectoryName = getString(R.string.app_name).replace(" ", ""); File imageStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName); if (!imageStorageDir.exists()) { //noinspection ResultOfMethodCallIgnored imageStorageDir.mkdirs(); } // create an image file name imageStorageDir = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg"); return imageStorageDir; } // openFileChooser for Android 3.0+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { String appDirectoryName = getString(R.string.app_name).replace(" ", ""); mUploadMessage = uploadMsg; try { File imageStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appDirectoryName); if (!imageStorageDir.exists()) { //noinspection ResultOfMethodCallIgnored imageStorageDir.mkdirs(); } File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg"); mCapturedImageURI = Uri.fromFile(file); // save to the private variable final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI); //captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); Intent chooserIntent = Intent.createChooser(i, getString(R.string.chooseAnImage)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent }); startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE); } catch (Exception e) { Toast.makeText(getApplicationContext(), ("Camera Exception"), Toast.LENGTH_LONG).show(); } } // openFileChooser for other Android versions /** * may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser() * https://code.google.com/p/android/issues/detail?id=62220 * however newer versions of KitKat fixed it on some devices */ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { openFileChooser(uploadMsg, acceptType); } }); // OnLongClickListener for detecting long clicks on links and images // !!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!! webViewFacebook.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // activate long clicks on links and image links according to settings if (true) { WebView.HitTestResult result = webViewFacebook.getHitTestResult(); if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) { Message msg = linkHandler.obtainMessage(); webViewFacebook.requestFocusNodeHref(msg); return true; } } return false; } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }
From source file:com.phonegap.plugins.ChildBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load.// ww w . jav a 2s . c o m * @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); toolbar.setVisibility(View.GONE); // 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); actionButtonContainer.setVisibility(View.GONE); // 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/images/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/images/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/images/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 ""; }