List of usage examples for android.webkit WebView getContext
@ViewDebug.CapturedViewProperty public final Context getContext()
From source file:com.urbantamil.projmadurai.CustomWebViewClient.java
@Override public void onPageFinished(WebView view, String url) { if (--running == 0) { // just "running--;" if you add a timer. // TODO: finished... if you want to fire a method. if (btn != null) { btn.setText(R.string.projmad_open_browser); btn.setEnabled(true);/*from ww w . j av a 2 s.c om*/ } /// interesting pieces to horizontal scroll ObservableWebView myWebView = (ObservableWebView) view; String varMySheet = "var mySheet = document.styleSheets[0];"; String addCSSRule = "function addCSSRule(selector, newRule) {" + "ruleIndex = mySheet.cssRules.length;" + "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);" + "}"; String insertRule1 = "addCSSRule('html', 'padding: 0px; height: " + (myWebView.getMeasuredHeight() / view.getContext().getResources().getDisplayMetrics().density) + "px; -webkit-column-gap: 0px; -webkit-column-width: " + myWebView.getMeasuredWidth() + "px;')"; myWebView.loadUrl("javascript:" + varMySheet); myWebView.loadUrl("javascript:" + addCSSRule); myWebView.loadUrl("javascript:" + insertRule1); } }
From source file:net.olejon.spotcommander.WebViewActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Google API client mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build(); // Allow landscape? if (!mTools.allowLandscape()) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Hide status bar? if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR")) getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Power manager final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); //noinspection deprecation mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock"); // Settings/*from ww w .j a va 2s . c o m*/ mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false); // Current network mCurrentNetwork = mTools.getCurrentNetwork(); // Computer final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID"); final String[] computer = mTools.getComputer(computerId); final String uri = computer[0]; final String username = computer[1]; final String password = computer[2]; // Layout setContentView(R.layout.activity_webview); // Status bar color if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mStatusBarPrimaryColor = getWindow().getStatusBarColor(); mStatusBarCoverArtColor = mStatusBarPrimaryColor; } // Notification mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN); if (mPersistentNotificationIsSupported) { final Intent launchActivityIntent = new Intent(mContext, MainActivity.class); launchActivityIntent.setAction("android.intent.action.MAIN"); launchActivityIntent.addCategory("android.intent.category.LAUNCHER"); mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class); hideIntent.setAction("hide_notification"); hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class); previousIntent.setAction("previous"); previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class); playPauseIntent.setAction("play_pause"); playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class); nextIntent.setAction("next"); nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class); volumeDownIntent.setAction("adjust_spotify_volume_down"); volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class); volumeUpIntent.setAction("adjust_spotify_volume_up"); volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId); mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent, PendingIntent.FLAG_CANCEL_CURRENT); mNotificationManager = NotificationManagerCompat.from(mContext); mNotificationBuilder = new NotificationCompat.Builder(mContext); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) mNotificationBuilder.setPriority(Notification.PRIORITY_MAX); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); mNotificationBuilder.setCategory(Notification.CATEGORY_TRANSPORT); } } // Web view mWebView = (WebView) findViewById(R.id.webview_webview); mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background)); mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); mWebView.setWebViewClient(new WebViewClient() { @SuppressWarnings("deprecation") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && !url.contains(uri) && !url.contains("olejon.net/code/spotcommander/api/1/spotify/") && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } return false; } @Override public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host, String realm) { if (handler.useHttpAuthUsernamePassword()) { handler.proceed(username, password); } else { handler.cancel(); mWebView.stopLoading(); mTools.showToast(getString(R.string.webview_authentication_failed), 1); mTools.navigateUp(mActivity); } } @Override public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) { mWebView.stopLoading(); mTools.showToast(getString(R.string.webview_error), 1); mTools.navigateUp(mActivity); } @Override public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) { handler.cancel(); mWebView.stopLoading(); new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title) .content(getString(R.string.webview_dialog_ssl_error_message)) .positiveText(R.string.webview_dialog_ssl_error_positive_button) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { finish(); } }).contentColorRes(R.color.black).show(); } }); // User agent mProjectVersionName = mTools.getProjectVersionName(); final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : ""; final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : ""; final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS")) ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D " : ""; // Web settings final WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(), mProjectVersionName, uaAppend1, uaAppend2, uaAppend3)); // Load app if (savedInstanceState != null) { mWebView.restoreState(savedInstanceState); } else { mWebView.loadUrl(uri); } // JavaScript interface mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android"); }
From source file:com.normalexception.app.rx8club.view.threadpost.PostView.java
/** * Setup our view here. After the view has been inflated and all of the * view objects have been initialized, we can inflate our view here * @param post The model we are going to use to populate the view * @param position Get the position of this view on the window * @param listener The listener object to attach to the view *///from ww w .j av a 2 s .c o m public void setPost(final PostModel post, final int position, final OnClickListener listener) { username.setText(post.getUserName()); userTitle.setText(post.getUserTitle()); userPosts.setText(post.getUserPostCount()); userJoin.setText(post.getJoinDate()); postDate.setText(post.getPostDate()); reportbutton.setVisibility(View.VISIBLE); if (PreferenceHelper.isShowLikes(getContext())) { if (post.getLikes().size() > 0) { String delim = "", likes = "Liked by: "; for (String like : post.getLikes()) { likes += delim + like; delim = ", "; } likeText.setText(likes); } else { likeText.setVisibility(View.GONE); } } else { likeText.setVisibility(View.GONE); } // Lets make sure we remove any font formatting that was done within // the text String trimmedPost = post.getUserPost().replaceAll("(?i)<(/*)font(.*?)>", ""); // Show attachments if the preference allows it if (PreferenceHelper.isShowAttachments(getContext())) trimmedPost = appendAttachments(trimmedPost, post.getAttachments()); // Show signatures if the preference allows it if (PreferenceHelper.isShowSignatures(getContext()) && post.getUserSignature() != null) trimmedPost = appendSignature(trimmedPost, post.getUserSignature()); // Set html Font color trimmedPost = Utils.postFormatter(trimmedPost, getContext()); postText.setBackgroundColor(Color.DKGRAY); postText.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); postText.getSettings().setAppCachePath(Cache.getExternalCacheDir(getContext()).getAbsolutePath()); postText.getSettings().setAllowFileAccess(false); postText.getSettings().setAppCacheEnabled(true); postText.getSettings().setJavaScriptEnabled(false); postText.getSettings().setSupportZoom(false); postText.getSettings().setSupportMultipleWindows(false); postText.getSettings().setUserAgentString(WebUrls.USER_AGENT); postText.getSettings().setDatabaseEnabled(false); postText.getSettings().setDomStorageEnabled(false); postText.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); postText.setOnTouchListener(new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { return (event.getAction() == MotionEvent.ACTION_MOVE); } }); postText.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // Check if the URL for the site, and if it is a thread or a category Log.d(TAG, "User Clicked Embedded url"); boolean isThread = false; if (url.contains("rx8club.com")) { isThread = url.matches(".*\\-\\d+\\/$"); Log.d(TAG, String.format("The Link (%s) is %sa thread", url, (isThread) ? "" : "NOT ")); Bundle args = new Bundle(); args.putString("link", url); if (isThread) { FragmentUtils.fragmentTransaction((FragmentActivity) view.getContext(), ThreadFragment.newInstance(), false, true, args); return true; } } // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainApplication.getAppContext().startActivity(intent); return true; } }); postText.loadDataWithBaseURL(WebUrls.rootUrl, trimmedPost, "text/html", "utf-8", ""); // Load up the avatar of hte user, but remember to remove // the dateline at the end of the file so that we aren't // creating multiple images for a user. The image still // gets returned without a date if (PreferenceHelper.isShowAvatars(getContext())) { String nodate_avatar = post.getUserImageUrl().indexOf('?') == -1 ? post.getUserImageUrl() : post.getUserImageUrl().substring(0, post.getUserImageUrl().indexOf('?')); if (!nodate_avatar.isEmpty()) { imageLoader.DisplayImage(nodate_avatar, avatar); } else { avatar.setImageResource(R.drawable.rotor_icon); } } // Display the right items if the user is logged in setUserIcons(this, post.isLoggedInUser()); downButton.setOnClickListener(listener); // Set click listeners if we are logged in, hide the buttons // if we are not logged in if (LoginFactory.getInstance().isGuestMode()) { quoteButton.setVisibility(View.GONE); editButton.setVisibility(View.GONE); pmButton.setVisibility(View.GONE); deleteButton.setVisibility(View.GONE); reportbutton.setVisibility(View.GONE); } else { quoteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.d(TAG, "Quote Clicked"); String txt = Html.fromHtml(post.getUserPost()).toString(); String finalText = String.format("[quote=%s]%s[/quote]", post.getUserName(), txt); postBox.setText(finalText); postBox.requestFocus(); } }); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.d(TAG, "Edit Clicked"); // Create new fragment and transaction Bundle args = new Bundle(); args.putString("postid", post.getPostId()); args.putString("securitytoken", post.getToken()); Fragment newFragment = new EditPostFragment(); FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment, true, true, args); } }); reportbutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.d(TAG, "Report Clicked"); new ReportPostDialog(getContext(), post.getToken(), post.getPostId()).show(); } }); linkbutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.d(TAG, "Link Clicked"); ClipboardManager clipboard = (android.content.ClipboardManager) getContext() .getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("thread link", post.getRootThreadUrl()); clipboard.setPrimaryClip(clip); Toast.makeText(getContext(), "Thread Link Copied To Clipboard", Toast.LENGTH_LONG).show(); } }); pmButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.d(TAG, "PM Clicked"); // Create new fragment and transaction Bundle args = new Bundle(); args.putString("user", post.getUserName()); Fragment newFragment = new NewPrivateMessageFragment(); FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment, false, true, args); } }); final boolean isFirstPost = (position == 0); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: // Create new fragment and transaction Bundle args = new Bundle(); args.putString("postid", post.getPostId()); args.putString("securitytoken", post.getToken()); args.putBoolean("delete", true); args.putBoolean("deleteThread", isFirstPost && post.isLoggedInUser()); Fragment newFragment = new EditPostFragment(); FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment, false, true, args); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage("Are you sure you want to delete your post?") .setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } }); } }
From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java
private void setWebChromeClientThatHandlesAlertsAsDialogs() { webView.setWebChromeClient(new WebChromeClient() { @Override//from w w w.j a va 2 s .c o m 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); } @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { Log.d(PacoConstants.TAG, message + " -- From line " + lineNumber + " of " + sourceID); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { Log.d(PacoConstants.TAG, consoleMessage.message() + " -- From line " + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId()); return true; } }); }
From source file:net.basov.ticketinfo.UI.java
public void displayMainScreen(final WebView wv) { wv.setWebViewClient(new MyWebViewClient() { @Override/* w w w .j a v a 2 s . c o m*/ public void onPageFinished(WebView view, String url) { super.onPageFinished(wv, url); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { view.evaluateJavascript("javascript:jreplace('" + header_json.toString() + "')", null); view.evaluateJavascript("javascript:jreplace('" + ticket_json.toString() + "')", null); view.evaluateJavascript("javascript:jreplace('" + ic_json.toString() + "')", null); view.evaluateJavascript("javascript:jreplace('" + dump_json.toString() + "')", null); } else { view.loadUrl("javascript:jreplace('" + header_json.toString() + "')"); view.loadUrl("javascript:jreplace('" + ticket_json.toString() + "')"); view.loadUrl("javascript:jreplace('" + ic_json.toString() + "')"); view.loadUrl("javascript:jreplace('" + dump_json.toString() + "')"); } wv.clearCache(true); wv.clearHistory(); //TODO: remove debug //Log.d("hhhh", header_json.toString()); //Log.d("tttt", ticket_json.toString()); //Log.d("iiii", ic_json.toString()); } }); Context c = wv.getContext(); wv.loadUrl("file:///android_asset/" + c.getString(R.string.ticket_ui_file)); }
From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java
private Cookie checkAntiDDOS(final CloudflareException exception, final HttpHost proxy, CancellableTask task, final Activity activity) { synchronized (lock) { if (processing) return null; processing = true;//from w ww . ja v a2 s . c om } processing2 = true; currentCookie = null; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { CookieSyncManager.createInstance(activity); CookieManager.getInstance().removeAllCookie(); } else { CompatibilityImpl.clearCookies(CookieManager.getInstance()); } final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView(); final WebViewClient client = new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onPageFinished(WebView webView, String url) { super.onPageFinished(webView, url); Logger.d(TAG, "Got Page: " + url); String value = null; try { String[] cookies = CookieManager.getInstance().getCookie(url).split("[;]"); for (String cookie : cookies) { if ((cookie != null) && (!cookie.trim().equals("")) && (cookie.startsWith(" " + exception.getRequiredCookieName() + "="))) { value = cookie.substring(exception.getRequiredCookieName().length() + 2); } } } catch (NullPointerException e) { Logger.e(TAG, e); } if (value != null) { BasicClientCookieHC4 cf_cookie = new BasicClientCookieHC4(exception.getRequiredCookieName(), value); cf_cookie.setDomain("." + Uri.parse(url).getHost()); cf_cookie.setPath("/"); currentCookie = cf_cookie; Logger.d(TAG, "Cookie found: " + value); processing2 = false; } else { Logger.d(TAG, "Cookie is not found"); } } }; activity.runOnUiThread(new Runnable() { @SuppressLint("SetJavaScriptEnabled") @Override public void run() { webView = new WebView(activity); webView.setVisibility(View.GONE); layout.addView(webView); webView.setWebViewClient(client); webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING); webView.getSettings().setJavaScriptEnabled(true); webViewContext = webView.getContext(); if (proxy != null) WebViewProxy.setProxy(webViewContext, proxy.getHostName(), proxy.getPort()); webView.loadUrl(exception.getCheckUrl()); } }); long startTime = System.currentTimeMillis(); while (processing2) { long time = System.currentTimeMillis() - startTime; if ((task != null && task.isCancelled()) || time > TIMEOUT) { processing2 = false; } } activity.runOnUiThread(new Runnable() { @Override public void run() { try { layout.removeView(webView); webView.stopLoading(); webView.clearCache(true); webView.destroy(); webView = null; } finally { if (proxy != null) WebViewProxy.setProxy(webViewContext, null, 0); processing = false; } } }); return currentCookie; }