List of usage examples for android.webkit WebViewClient WebViewClient
WebViewClient
From source file:de.appplant.cordova.plugin.printer.Printer.java
/** * Creates the web view client which sets the print document. * * @param props//from w ww. ja va 2s . c om * The JSON object with the containing page properties */ private void setWebViewClient(JSONObject props) { final String docName = props.optString("name", DEFAULT_DOC_NAME); final boolean landscape = props.optBoolean("landscape", false); final boolean graystyle = props.optBoolean("graystyle", false); view.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } @Override public void onPageFinished(WebView webView, String url) { // Get a PrintManager instance PrintManager printManager = (PrintManager) cordova.getActivity() .getSystemService(Context.PRINT_SERVICE); // Get a print adapter instance PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(); // Get a print builder instance PrintAttributes.Builder builder = new PrintAttributes.Builder(); // The page does itself set its own margins builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS); builder.setColorMode( graystyle ? PrintAttributes.COLOR_MODE_MONOCHROME : PrintAttributes.COLOR_MODE_COLOR); builder.setMediaSize(landscape ? PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE : PrintAttributes.MediaSize.UNKNOWN_PORTRAIT); // Create a print job with name and adapter instance PrintJob job = printManager.print(docName, printAdapter, builder.build()); invokeCallbackOnceCompletedOrCanceled(job); view = null; } }); }
From source file:prince.app.ccm.Fragment_Turnos.java
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Tell the MultiSwipeRefreshLayout which views are swipeable. mSwipeRefreshLayout.setSwipeableChildren(R.id.text_audio_main); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override/*from ww w .j a v a2 s. c o m*/ public void onRefresh() { Log.i(TAG, "onRefreshListener launched"); if (Tool.getInstance().isConnection()) { refreshPage(); } else { Toast.makeText(getActivity(), getResources().getString(R.string.no_connection), Toast.LENGTH_LONG).show(); // Stop the refreshing indicator mSwipeRefreshLayout.setRefreshing(false); } } }); schedule.setWebViewClient(new WebViewClient() { public void onPageStarted(WebView view, String url, Bitmap favicon) { // hide the webView schedule.setVisibility(View.INVISIBLE); mProgress.setVisibility(View.VISIBLE); Log.e(TAG, "starting download at: " + Tool.time()); } public void onPageFinished(WebView view, String url) { // Stop the refreshing indicator mSwipeRefreshLayout.setRefreshing(false); // show the webView schedule.setVisibility(View.VISIBLE); mProgress.setVisibility(View.INVISIBLE); Log.e(TAG, "finished downloading at: " + Tool.time()); } public void onReceivedError(WebView view, int errorCod, String description, String failingUrl) { // mCallback.onPageError(); handleError(); } }); }
From source file:com.concentricsky.android.khanacademy.app.ShowProfileActivity.java
/** * Get the current user, and fail if there is none. *///from w w w . j a va 2s . co m @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); destroyed = false; this.webViewTimeoutPromptDialog = new AlertDialog.Builder(this) .setMessage("The page is taking a long time to respond. Stop loading?") .setPositiveButton("Stop", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (webView != null) { webView.stopLoading(); finish(); } } }).setNegativeButton("Wait", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { stopWebViewLoadTimeout(); } }).setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { startWebViewLoadTimeout(); } }).create(); getActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.profile); setTitle(getString(R.string.profile_title)); webView = (WebView) findViewById(R.id.web_view); webView.setMinimumWidth(800); enableJavascript(webView); webView.getSettings().setDefaultZoom(ZoomDensity.FAR); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { Log.d(LOG_TAG, "shouldOverrideUrlLoading: " + url); URL parsed = null; try { parsed = new URL(url); } catch (MalformedURLException e) { // Let the webview figure that one out. return false; } // Only ka links will load in this webview. if (parsed.getHost().equals("www.khanacademy.org")) { // Video urls should link into video detail. See below for another video url format. if (parsed.getPath().equals("/video")) { String query = parsed.getQuery(); if (query != null && query.length() > 0) { String[] items = query.split("&"); String videoId = null; for (String item : items) { String[] parts = item.split("=", 2); if (parts.length > 1) { if ("v".equals(parts[0])) { videoId = parts[1]; break; } } } if (videoId != null) { String[] ids = normalizeVideoAndTopicId(videoId, ""); if (ids != null) { launchVideoDetailActivity(ids[0], ids[1]); return true; } } } // There was no ?v= or something weird is going on. Allow the page // load, which should hit KA's nice "no video found" page. showSpinner(); startWebViewLoadTimeout(); return false; } if (parsed.getPath().startsWith("/profile")) { // navigation within the profile makes sense here. showSpinner(); startWebViewLoadTimeout(); return false; } // Embedded logout option (in upper left menu) can be intercepted and cause the app to be logged out as well. if (parsed.getPath().equals("/logout")) { if (dataService != null) { dataService.getAPIAdapter().logout(); } finish(); return false; // try to let the webview hit logout to get the cookies cleared as we exit } // There is a new kind of video url now.. thanks guys.. // http://www.khanacademy.org/video/subtraction-2 // redirects to // http://www.khanacademy.org/math/arithmetic/addition-subtraction/two_dig_add_sub/v/subtraction-2 String[] path = parsed.getPath().split("/"); List<String> parts = Arrays.asList(path); if (parts.contains("v")) { String videoId = null; String topicId = null; for (int i = path.length - 1; i >= 0; --i) { if (path[i].equals("v")) { continue; } if (videoId == null) { videoId = path[i]; } else if (topicId == null) { topicId = path[i]; } else { break; } } if (videoId != null && topicId != null && dataService != null) { // Looks like a video url. Double check that we have the topic and video before launching detail activity. Log.d(LOG_TAG, "video and topic ids found; looks like a video url."); String[] ids = normalizeVideoAndTopicId(videoId, topicId); if (ids != null) { launchVideoDetailActivity(ids[0], ids[1]); return true; } } } else if (parsed.getPath().startsWith("/video")) { String videoId = path[path.length - 1]; String[] ids = normalizeVideoAndTopicId(videoId, ""); if (ids != null) { launchVideoDetailActivity(ids[0], ids[1]); return true; } } // showSpinner(); // startWebViewLoadTimeout(); // return false; } // All other urls should launch in the browser instead of here, except hash changes if we can distinguish. loadInBrowser(url); return true; } @Override public void onPageFinished(WebView view, String url) { Log.d(LOG_TAG, "onPageFinished"); stopWebViewLoadTimeout(); if (!destroyed) { hideSpinner(); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.d(LOG_TAG, "onPageStarted"); stopWebViewLoadTimeout(); // view.loadUrl("javascript:document.addEventListener( 'DOMContentLoaded',function() {AndroidApplication.jqueryReady()} );"); // handler.postDelayed(new Runnable() { // @Override // public void run() { // if (!destroyed) { // hijack(); // } // } // }, 100); } }); // webView.addJavascriptInterface(new Object() { // public void log(String msg) { // Log.d(LOG_TAG, "JSLOG: " + msg); // } // public void jqueryReady() { // Log.d(LOG_TAG, "javascript: jqueryReady"); // hijack(); // } // }, "AndroidApplication"); // showSpinner(); requestDataService(new ObjectCallback<KADataService>() { @Override public void call(KADataService service) { dataService = service; api = service.getAPIAdapter(); String[] credentials = getCurrentLoginCredentials(); loginUser(credentials[0], credentials[1]); } }); }
From source file:org.digitalcampus.oppia.widgets.PageWidget.java
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); wv = (WebView) super.getActivity().findViewById(activity.getActId()); // get the location data String url = course.getLocation() + activity .getLocation(prefs.getString(PrefsActivity.PREF_LANGUAGE, Locale.getDefault().getLanguage())); int defaultFontSize = Integer.parseInt(prefs.getString(PrefsActivity.PREF_TEXT_SIZE, "16")); wv.getSettings().setDefaultFontSize(defaultFontSize); try {/*from w w w . java 2s. co m*/ wv.getSettings().setJavaScriptEnabled(true); //We inject the interface to launch intents from the HTML wv.addJavascriptInterface(new JSInterfaceForResourceImages(this.getActivity(), course.getLocation()), JSInterfaceForResourceImages.InterfaceExposedName); wv.loadDataWithBaseURL("file://" + course.getLocation() + File.separator, FileUtils.readFile(url), "text/html", "utf-8", null); } catch (IOException e) { wv.loadUrl("file://" + url); } wv.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { //We execute the necessary JS code to bind click on images with our JavascriptInterface view.loadUrl(JSInterfaceForResourceImages.JSInjection); } // set up the page to intercept videos @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("/video/")) { // extract video name from url int startPos = url.indexOf("/video/") + 7; String mediaFileName = url.substring(startPos, url.length()); // check video file exists boolean exists = FileUtils.mediaFileExists(PageWidget.super.getActivity(), mediaFileName); if (!exists) { Log.d(TAG, PageWidget.super.getActivity().getString(R.string.error_media_not_found, mediaFileName)); Toast.makeText(PageWidget.super.getActivity(), PageWidget.super.getActivity() .getString(R.string.error_media_not_found, mediaFileName), Toast.LENGTH_LONG) .show(); return true; } else { Log.d(TAG, "Media found: " + mediaFileName); } String mimeType = FileUtils .getMimeType(FileUtils.getMediaPath(PageWidget.super.getActivity()) + mediaFileName); if (!FileUtils.supportedMediafileType(mimeType)) { Toast.makeText(PageWidget.super.getActivity(), PageWidget.super.getActivity() .getString(R.string.error_media_unsupported, mediaFileName), Toast.LENGTH_LONG) .show(); return true; } Intent intent = new Intent(PageWidget.super.getActivity(), VideoPlayerActivity.class); Bundle tb = new Bundle(); tb.putSerializable(VideoPlayerActivity.MEDIA_TAG, mediaFileName); tb.putSerializable(Activity.TAG, activity); tb.putSerializable(Course.TAG, course); intent.putExtras(tb); startActivity(intent); return true; } else { try { Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse(url); intent.setData(data); PageWidget.super.getActivity().startActivity(intent); } catch (ActivityNotFoundException anfe) { // do nothing } // launch action in mobile browser - not the webview // return true so doesn't follow link within webview return true; } } }); }
From source file:com.twitter4rk.TwitterAuthFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mTwitterWebView = new WebView(getActivity()); final Bundle args = getArguments(); if (args == null) { // This wont be case because startTwitterAuth() handles args for // fragment throw new IllegalArgumentException( "No arguments passed to fragment, Please use startTwitterAuth(...) method for showing this fragment"); }// w w w. j av a2s . c om // Get builder from args mBuilder = args.getParcelable(BUILDER_KEY); // Hide action bar if (mBuilder.hideActionBar) mBuilder.activity.getActionBar().hide(); // Init progress dialog mProgressDialog = new ProgressDialog(mBuilder.activity); mProgressDialog.setMessage(mBuilder.progressText == null ? "Loading ..." : mBuilder.progressText); if (mBuilder.isProgressEnabled) mProgressDialog.show(); // Init ConfigurationBuilder twitter4j final ConfigurationBuilder cb = new ConfigurationBuilder(); if (mBuilder.isDebugEnabled) cb.setDebugEnabled(true); cb.setOAuthConsumerKey(mBuilder.consumerKey); cb.setOAuthConsumerSecret(mBuilder.consumerSecret); // Web view client to handler url loading mTwitterWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // Get url first final Uri uri = Uri.parse(url); // Check if we need to see for callback URL if (mBuilder.callbackUrl != null && url.contains(mBuilder.callbackUrl)) { // Get req info String oauthToken = uri.getQueryParameter("oauth_token"); String oauthVerifier = uri.getQueryParameter("oauth_verifier"); if (mListener != null) mListener.onSuccess(oauthToken, oauthVerifier); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); mIsAuthenticated = true; removeMe(); return true; // If no callback URL then check for info directly } else if (uri.getQueryParameter("oauth_token") != null && uri.getQueryParameter("oauth_verifier") != null) { // Get req info String oauthToken = uri.getQueryParameter("oauth_token"); String oauthVerifier = uri.getQueryParameter("oauth_verifier"); if (mListener != null) mListener.onSuccess(oauthToken, oauthVerifier); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); mIsAuthenticated = true; removeMe(); return true; // If nothing then its failure } else { // Notify user if (mListener != null) mListener.onFailure( new Exception("Couldn't find the callback URL or oath parameters in response")); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); removeMe(); return false; } } }); // Web Crome client to handler progress dialog visibility mTwitterWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { if (mProgressDialog.isShowing()) mProgressDialog.dismiss(); } } }); final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { try { final TwitterFactory twitterFactory = new TwitterFactory(cb.build()); final Twitter twitter = twitterFactory.getInstance(); RequestToken requestToken = null; if (mBuilder.callbackUrl == null) requestToken = twitter.getOAuthRequestToken(); else requestToken = twitter.getOAuthRequestToken(mBuilder.callbackUrl); final RequestToken finalRequestToken = requestToken; handler.post(new Runnable() { @Override public void run() { final String url = finalRequestToken.getAuthorizationURL(); mTwitterWebView.loadUrl(url); } }); } catch (TwitterException e) { e.printStackTrace(); } } }).start(); return mTwitterWebView; }
From source file:com.pursuer.reader.easyrss.WebpageItemViewCtrl.java
@SuppressLint("SetJavaScriptEnabled") public WebpageItemViewCtrl(final DataMgr dataMgr, final Context context, final String uid, final boolean isMobilized) { super(dataMgr, R.layout.webpage_item, context); this.item = dataMgr.getItemByUid(uid, ITEM_PROJECTION); this.theme = new SettingTheme(dataMgr).getData(); this.fontSize = new SettingFontSize(dataMgr).getData(); // 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); }/*from ww w . ja v a2 s. c o m*/ { mobilizedView = (WebView) view.findViewById(R.id.MobilizedContent); mobilizedView.setBackgroundColor(context.getResources().getColor( theme == SettingTheme.THEME_NORMAL ? R.color.NormalBackground : R.color.DarkBackground)); mobilizedView.setFocusable(false); final WebSettings settings = mobilizedView.getSettings(); settings.setDefaultTextEncodingName(HTTP.UTF_8); settings.setJavaScriptEnabled(false); settings.setDefaultFontSize(fontSize); } { originalView = (WebView) view.findViewById(R.id.OriginalContent); originalView.setFocusable(false); originalView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); final WebSettings settings = originalView.getSettings(); settings.setJavaScriptEnabled(true); settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); originalView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(final WebView webView, final String url) { view.findViewById(R.id.OriginalProgress).setVisibility(View.GONE); } @Override public void onPageStarted(final WebView webView, final String url, final Bitmap favicon) { if (!showMobilized) { view.findViewById(R.id.OriginalProgress).setVisibility(View.VISIBLE); } } @Override public boolean shouldOverrideUrlLoading(final WebView webView, final String url) { webView.loadUrl(url); return false; } }); } if (isMobilized) { showMobilizedPage(); } else { showOriginalPage(); } view.findViewById(R.id.BtnMobilzedPage).setOnClickListener(new OnClickListener() { @Override public void onClick(final View view) { showMobilizedPage(); } }); view.findViewById(R.id.BtnOriginalPage).setOnClickListener(new OnClickListener() { @Override public void onClick(final View view) { showOriginalPage(); } }); view.findViewById(R.id.BtnClose).setOnClickListener(new OnClickListener() { @Override public void onClick(final View view) { if (listener != null) { listener.onBackNeeded(); } } }); }
From source file:com.androzic.waypoint.WaypointInfo.java
@SuppressLint("NewApi") private void updateWaypointInfo(double lat, double lon) { Androzic application = Androzic.getApplication(); Activity activity = getActivity();/*from w ww.j av a 2 s . co m*/ Dialog dialog = getDialog(); View view = getView(); WebView description = (WebView) view.findViewById(R.id.description); if ("".equals(waypoint.description)) { description.setVisibility(View.GONE); } else { String descriptionHtml; try { TypedValue tv = new TypedValue(); Theme theme = activity.getTheme(); Resources resources = getResources(); theme.resolveAttribute(android.R.attr.textColorSecondary, tv, true); int secondaryColor = resources.getColor(tv.resourceId); String css = String.format( "<style type=\"text/css\">html,body{margin:0;background:transparent} *{color:#%06X}</style>\n", (secondaryColor & 0x00FFFFFF)); descriptionHtml = css + waypoint.description; description.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { view.setBackgroundColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } }); description.setBackgroundColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) description.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); } catch (Resources.NotFoundException e) { description.setBackgroundColor(Color.LTGRAY); descriptionHtml = waypoint.description; } WebSettings settings = description.getSettings(); settings.setDefaultTextEncodingName("utf-8"); settings.setAllowFileAccess(true); Uri baseUrl = Uri.fromFile(new File(application.dataPath)); description.loadDataWithBaseURL(baseUrl.toString() + "/", descriptionHtml, "text/html", "utf-8", null); } String coords = StringFormatter.coordinates(" ", waypoint.latitude, waypoint.longitude); ((TextView) view.findViewById(R.id.coordinates)).setText(coords); if (waypoint.altitude != Integer.MIN_VALUE) { ((TextView) view.findViewById(R.id.altitude)).setText(StringFormatter.elevationH(waypoint.altitude)); } double dist = Geo.distance(lat, lon, waypoint.latitude, waypoint.longitude); double bearing = Geo.bearing(lat, lon, waypoint.latitude, waypoint.longitude); bearing = application.fixDeclination(bearing); String distance = StringFormatter.distanceH(dist) + " " + StringFormatter.angleH(bearing); ((TextView) view.findViewById(R.id.distance)).setText(distance); if (waypoint.date != null) ((TextView) view.findViewById(R.id.date)) .setText(DateFormat.getDateFormat(activity).format(waypoint.date) + " " + DateFormat.getTimeFormat(activity).format(waypoint.date)); else ((TextView) view.findViewById(R.id.date)).setVisibility(View.GONE); dialog.setTitle(waypoint.name); }
From source file:com.mimo.service.api.MimoOauth2Client.java
/** * Instantiate a webview and allows the user to login to the Api form within * the application// w w w .j av a 2 s. co m * * @param p_view * : Calling view * * @param p_activity * : Calling Activity reference **/ @SuppressLint("SetJavaScriptEnabled") public void login(View p_view, Activity p_activity) { final Activity m_activity; m_activity = p_activity; String m_url = this.m_api.getAuthUrl(); WebView m_webview = new WebView(p_view.getContext()); m_webview.getSettings().setJavaScriptEnabled(true); m_webview.setVisibility(View.VISIBLE); m_activity.setContentView(m_webview); m_webview.requestFocus(View.FOCUS_DOWN); /** * Open the softkeyboard of the device to input the text in form which * loads in webview. */ m_webview.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View p_v, MotionEvent p_event) { switch (p_event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (!p_v.hasFocus()) { p_v.requestFocus(); } break; } return false; } }); /** * Show the progressbar in the title of the activity untill the page * loads the give url. */ m_webview.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView p_view, int p_newProgress) { ((Activity) m_context).setProgress(p_newProgress * 100); ((Activity) m_context).setTitle(MimoAPIConstants.DIALOG_TEXT_LOADING); if (p_newProgress == 100) ((Activity) m_context).setTitle(m_context.getString(R.string.app_name)); } }); m_webview.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView p_view, String p_url, Bitmap p_favicon) { } @Override public void onReceivedHttpAuthRequest(WebView p_view, HttpAuthHandler p_handler, String p_url, String p_realm) { p_handler.proceed(MimoAPIConstants.USERNAME, MimoAPIConstants.PASSWORD); } public void onPageFinished(WebView p_view, String p_url) { if (MimoAPIConstants.DEBUG) { Log.d(TAG, "Page Url = " + p_url); } if (p_url.contains("?code=")) { if (p_url.indexOf("code=") != -1) { String[] m_urlSplit = p_url.split("="); String m_tempString1 = m_urlSplit[1]; if (MimoAPIConstants.DEBUG) { Log.d(TAG, "TempString1 = " + m_tempString1); } String[] m_urlSplit1 = m_tempString1.split("&"); String m_code = m_urlSplit1[0]; if (MimoAPIConstants.DEBUG) { Log.d(TAG, "code = " + m_code); } MimoOauth2Client.this.m_code = m_code; Thread m_thread = new Thread() { public void run() { String m_token = requesttoken(MimoOauth2Client.this.m_code); Log.d(TAG, "Token = " + m_token); Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class); m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token); m_activity.startActivity(m_navigateIntent); } }; m_thread.start(); } else { if (MimoAPIConstants.DEBUG) { Log.d(TAG, "going in else"); } } } else if (p_url.contains(MimoAPIConstants.URL_KEY_TOKEN)) { if (p_url.indexOf(MimoAPIConstants.URL_KEY_TOKEN) != -1) { String[] m_urlSplit = p_url.split("="); final String m_token = m_urlSplit[1]; Thread m_thread = new Thread() { public void run() { Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class); m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token); m_activity.startActivity(m_navigateIntent); } }; m_thread.start(); } } }; }); m_webview.loadUrl(m_url); }
From source file:com.maxleapmobile.gitmaster.ui.fragment.RecommendFragment.java
private void initUI(View view) { actionArea = (LinearLayout) view.findViewById(R.id.recommend_action_area); starProgressBar = (ProgressBar) view.findViewById(R.id.recommend_star_progressbar); starText = (TextView) view.findViewById(R.id.recommend_star); starText.setOnClickListener(this); view.findViewById(R.id.recommend_fork).setOnClickListener(this); skipBtn = view.findViewById(R.id.recommend_skip); skipBtn.setOnClickListener(this); mProgressBar = (ProgressBar) view.findViewById(R.id.repo_progressbar); TextView notice2 = (TextView) view.findViewById(R.id.recommend_notice2); SpannableString notice2SS = new SpannableString(mContext.getString(R.string.recommend_notice2_part1) + " " + mContext.getString(R.string.recommend_notice2_part2)); notice2SS.setSpan(new CustomClickableSpan(), 0, mContext.getString(R.string.recommend_notice2_part1).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); notice2.setText(notice2SS);// ww w . ja va2 s .c o m notice2.setOnClickListener(this); notice3 = (TextView) view.findViewById(R.id.recommend_notice3); final SpannableString notice3SS = new SpannableString(mContext.getString(R.string.recommend_notice3_part1) + " " + mContext.getString(R.string.recommend_notice3_part2)); notice3SS.setSpan(new CustomClickableSpan(), mContext.getString(R.string.recommend_notice3_part1).length(), notice3SS.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); notice3.setText(notice3SS); notice3.setOnClickListener(this); mWebView = (ProgressWebView) view.findViewById(R.id.recommend_webview); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mProgressBar.setVisibility(View.GONE); } }); mEmptyView = (LinearLayout) view.findViewById(R.id.recommend_empty); mEmptyView.setVisibility(View.GONE); if (mParmasMap == null) { mParmasMap = new HashMap(); mParmasMap.put("userid", username); mParmasMap.put("page", page); mParmasMap.put("per_page", PER_PAGE); } }
From source file:bolts.WebViewAppLinkResolver.java
@Override public Task<AppLink> getAppLinkFromUrlInBackground(final Uri url) { final Capture<String> content = new Capture<String>(); final Capture<String> contentType = new Capture<String>(); return Task.callInBackground(new Callable<Void>() { @Override/*from w w w. j a v a2 s .c o m*/ public Void call() throws Exception { URL currentURL = new URL(url.toString()); URLConnection connection = null; while (currentURL != null) { // Fetch the content at the given URL. connection = currentURL.openConnection(); if (connection instanceof HttpURLConnection) { // Unfortunately, this doesn't actually follow redirects if they go from http->https, // so we have to do that manually. ((HttpURLConnection) connection).setInstanceFollowRedirects(true); } connection.setRequestProperty(PREFER_HEADER, META_TAG_PREFIX); connection.connect(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; if (httpConnection.getResponseCode() >= 300 && httpConnection.getResponseCode() < 400) { currentURL = new URL(httpConnection.getHeaderField("Location")); httpConnection.disconnect(); } else { currentURL = null; } } else { currentURL = null; } } try { content.set(readFromConnection(connection)); contentType.set(connection.getContentType()); } finally { if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).disconnect(); } } return null; } }).onSuccessTask(new Continuation<Void, Task<JSONArray>>() { @Override public Task<JSONArray> then(Task<Void> task) throws Exception { // Load the content in a WebView and use JavaScript to extract the meta tags. final TaskCompletionSource<JSONArray> tcs = new TaskCompletionSource<>(); final WebView webView = new WebView(context); webView.getSettings().setJavaScriptEnabled(true); webView.setNetworkAvailable(false); webView.setWebViewClient(new WebViewClient() { private boolean loaded = false; private void runJavaScript(WebView view) { if (!loaded) { // After the first resource has been loaded (which will be the pre-populated data) // run the JavaScript meta tag extraction script loaded = true; view.loadUrl(TAG_EXTRACTION_JAVASCRIPT); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); runJavaScript(view); } @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); runJavaScript(view); } }); // Inject an object that will receive the JSON for the extracted JavaScript tags webView.addJavascriptInterface(new Object() { @JavascriptInterface public void setValue(String value) { try { tcs.trySetResult(new JSONArray(value)); } catch (JSONException e) { tcs.trySetError(e); } } }, "boltsWebViewAppLinkResolverResult"); String inferredContentType = null; if (contentType.get() != null) { inferredContentType = contentType.get().split(";")[0]; } webView.loadDataWithBaseURL(url.toString(), content.get(), inferredContentType, null, null); return tcs.getTask(); } }, Task.UI_THREAD_EXECUTOR).onSuccess(new Continuation<JSONArray, AppLink>() { @Override public AppLink then(Task<JSONArray> task) throws Exception { Map<String, Object> alData = parseAlData(task.getResult()); AppLink appLink = makeAppLinkFromAlData(alData, url); return appLink; } }); }