List of usage examples for android.webkit WebViewClient WebViewClient
WebViewClient
From source file:com.owncloud.android.ui.activity.ExternalSiteWebView.java
@Override protected void onCreate(Bundle savedInstanceState) { Log_OC.v(TAG, "onCreate() start"); Bundle extras = getIntent().getExtras(); String title = extras.getString(EXTRA_TITLE); String url = extras.getString(EXTRA_URL); menuItemId = extras.getInt(EXTRA_MENU_ITEM_ID); showSidebar = extras.getBoolean(EXTRA_SHOW_SIDEBAR); // show progress getWindow().requestFeature(Window.FEATURE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.externalsite_webview); WebView webview = (WebView) findViewById(R.id.webView); WebSettings webSettings = webview.getSettings(); webview.setFocusable(true);//from w ww . j a v a2 s .c om webview.setFocusableInTouchMode(true); webview.setClickable(true); // setup toolbar setupToolbar(); // setup drawer setupDrawer(menuItemId); if (!showSidebar) { setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } getSupportActionBar().setTitle(title); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // enable zoom webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); webSettings.setDisplayZoomControls(false); // Non-responsive webs are zoomed out when loaded webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); // user agent webSettings.setUserAgentString(MainApp.getUserAgent()); // no private data storing webSettings.setSavePassword(false); webSettings.setSaveFormData(false); // disable local file access webSettings.setAllowFileAccess(false); // enable javascript webview.getSettings().setJavaScriptEnabled(true); final Activity activity = this; final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar); webview.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { progressBar.setProgress(progress * 1000); } }); webview.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(activity, getString(R.string.webview_error) + ": " + description, Toast.LENGTH_SHORT) .show(); } }); webview.loadUrl(url); }
From source file:com.github.dfa.diaspora_android.activity.ShareActivity2.java
@SuppressLint("SetJavaScriptEnabled") @Override//from ww w . j a v a2 s. c om protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); progressBar = (ProgressBar) findViewById(R.id.progressBar); swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe); swipeView.setEnabled(false); toolbar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (Helpers.isOnline(ShareActivity2.this)) { Intent intent = new Intent(ShareActivity2.this, MainActivity.class); startActivityForResult(intent, 100); overridePendingTransition(0, 0); } else { Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show(); } } }); podDomain = ((App) getApplication()).getSettings().getPodDomain(); fab = (com.getbase.floatingactionbutton.FloatingActionsMenu) findViewById(R.id.fab_expand_menu_button); fab.setVisibility(View.GONE); webView = (WebView) findViewById(R.id.webView); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); WebSettings wSettings = webView.getSettings(); wSettings.setJavaScriptEnabled(true); wSettings.setBuiltInZoomControls(true); if (Build.VERSION.SDK_INT >= 21) wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); /* * WebViewClient */ webView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.d(TAG, url); if (!url.contains(podDomain)) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(i); return true; } return false; } public void onPageFinished(WebView view, String url) { Log.i(TAG, "Finished loading URL: " + url); } }); /* * WebChromeClient */ webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView wv, int progress) { progressBar.setProgress(progress); if (progress > 0 && progress <= 60) { Helpers.getNotificationCount(wv); } if (progress > 60) { Helpers.hideTopBar(wv); } if (progress == 100) { progressBar.setVisibility(View.GONE); } else { progressBar.setVisibility(View.VISIBLE); } } @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { 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 Snackbar.make(getWindow().findViewById(R.id.drawer_layout), "Unable to get image", Snackbar.LENGTH_SHORT).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, "Image Chooser"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); return true; } }); Intent intent = getIntent(); final Bundle extras = intent.getExtras(); String action = intent.getAction(); if (Intent.ACTION_SEND.equals(action)) { webView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { if (extras.containsKey(Intent.EXTRA_TEXT) && extras.containsKey(Intent.EXTRA_SUBJECT)) { final String extraText = (String) extras.get(Intent.EXTRA_TEXT); final String extraSubject = (String) extras.get(Intent.EXTRA_SUBJECT); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { finish(); Intent i = new Intent(ShareActivity2.this, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); overridePendingTransition(0, 0); return false; } }); webView.loadUrl("javascript:(function() { " + "document.getElementsByTagName('textarea')[0].style.height='110px'; " + "document.getElementsByTagName('textarea')[0].innerHTML = '**[" + extraSubject + "]** " + extraText + " *[shared with #DiasporaWebApp]*'; " + " if(document.getElementById(\"main_nav\")) {" + " document.getElementById(\"main_nav\").parentNode.removeChild(" + " document.getElementById(\"main_nav\"));" + " } else if (document.getElementById(\"main-nav\")) {" + " document.getElementById(\"main-nav\").parentNode.removeChild(" + " document.getElementById(\"main-nav\"));" + " }" + "})();"); } } }); } if (savedInstanceState == null) { if (Helpers.isOnline(ShareActivity2.this)) { webView.loadUrl("https://" + podDomain + "/status_messages/new"); } else { Snackbar.make(getWindow().findViewById(R.id.drawer_layout), R.string.no_internet, Snackbar.LENGTH_SHORT).show(); } } }
From source file:no.digipost.android.gui.metadata.ExternalLinkWebview.java
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((DigipostApplication) getApplication()).getTracker(DigipostApplication.TrackerName.APP_TRACKER); setContentView(R.layout.activity_externallink_webview); Bundle bundle = getIntent().getExtras(); fileUrl = bundle.getString("url", "https://www.digipost.no"); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);//from w w w. j av a 2 s . c om actionBar = getSupportActionBar(); if (actionBar != null) { setActionBarTitle(fileUrl); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setBackgroundDrawable(new ColorDrawable(0xff2E2E2E)); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = this.getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor( ContextCompat.getColor(this, R.color.metadata_externalbrowser_top_background)); } } progressSpinner = (ProgressBar) findViewById(R.id.externallink_spinner); webView = (WebView) findViewById(R.id.externallink_webview); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); settings.setDomStorageEnabled(true); settings.setLoadWithOverviewMode(true); settings.setUseWideViewPort(true); settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); settings.setDisplayZoomControls(false); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(true); enableCookies(webView); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (firstLoad) { progressSpinner.setVisibility(View.GONE); webView.setVisibility(View.VISIBLE); firstLoad = false; } setActionBarTitle(view.getUrl()); } }); webView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(final String url, final String userAgent, final String content, final String mimeType, final long contentLength) { fileName = URLUtil.guessFileName(url, content, mimeType); fileUrl = url; onComplete = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { showDownloadSuccessDialog(context); } } }; registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); if (!mimeType.equals("text/html")) { if (FileUtilities.isStorageWriteAllowed(getApplicationContext())) { showDownloadDialog(userAgent, content, mimeType, contentLength); } else { showMissingPermissionsDialog(); } } } }); if (FileUtilities.isStorageWriteAllowed(this)) { webView.loadUrl(fileUrl); } else { showPermissionsDialog(); } }
From source file:com.concentricsky.android.khanacademy.app.SignInActivity.java
/** * Set up a url filter to catch our callback, then start a request token operation. *///ww w. j a v a 2 s . c om @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); setTitle("Log in"); // Show no activity transition animation; we want to appear as if we're the same activity as the underlying ShowProfileActivity. overridePendingTransition(0, 0); setContentView(R.layout.popover_web); webView = (WebView) findViewById(R.id.web_view); enableJavascript(webView); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { showSpinner(); Log.d(LOG_TAG, ">>>>>>>>>>>>> url: " + url); if (url.contains(OAUTH_CALLBACK_URL)) { currentTasks.add(new AccessTokenFetcher().execute(url)); return true; } return false; } @Override public void onPageFinished(WebView view, String url) { hideSpinner(); } }); showSpinner(); requestDataService(new ObjectCallback<KADataService>() { @Override public void call(KADataService service) { consumer = service.getAPIAdapter().getConsumer(null); currentTasks.add(new RequestTokenFetcher().execute()); } }); }
From source file:com.bangalore.barcamp.activity.WebViewActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview);//from w ww .ja v a2 s . c o m mDrawerToggle = BCBFragmentUtils.setupActionBar(this, BCBConsts.BARCAMP_BANGALORE); webView = (WebView) findViewById(R.id.webView); WebSettings websettings = webView.getSettings(); websettings.setJavaScriptEnabled(true); webView.setClickable(true); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { if (url.contains("bcbapp://android")) { setUserDetails(url); } super.onPageStarted(view, url, favicon); } private void setUserDetails(String url) { Intent newIntent = new Intent(WebViewActivity.this, MainFragmentActivity.class); newIntent.setData(Uri.parse(url)); startActivity(newIntent); String id = newIntent.getData().getQueryParameter("id"); String sid = newIntent.getData().getQueryParameter("sid"); Log.e("data", "id: " + id + " sid: " + sid); BCBSharedPrefUtils.setUserData(getApplicationContext(), id, sid); BCBSharedPrefUtils.setScheduleUpdated(WebViewActivity.this, true); finish(); } @Override public void onPageFinished(WebView view, String url) { findViewById(R.id.linearLayout2).setVisibility(View.GONE); webView.setVisibility(View.VISIBLE); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { showDialog(SHOW_ERROR_DIALOG); } @Override public void onLoadResource(WebView view, String url) { if (url.contains("bcbapp://android")) { setUserDetails(url); Tracker t = ((BarcampBangalore) getApplication()).getTracker(); // Send a screen view. t.send(new HitBuilders.EventBuilder().setCategory("ui_action").setAction("button") .setLabel("Login Success").build()); } super.onLoadResource(view, url); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("bcbapp://android")) { setUserDetails(url); Tracker t = ((BarcampBangalore) getApplication()).getTracker(); // Send a screen view. t.send(new HitBuilders.EventBuilder().setCategory("ui_action").setAction("button") .setLabel("Login Success").build()); return true; } if (url.equals(getIntent().getStringExtra(URL))) { return true; } else if (getIntent().getBooleanExtra(ENABLE_LOGIN, false)) { return false; } Log.e("Action", url); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); return true; } }); String url = getIntent().getStringExtra(URL); webView.loadUrl(url); Tracker t = ((BarcampBangalore) getApplication()).getTracker(); // Set screen name. t.setScreenName(this.getClass().getName() + url); // Send a screen view. t.send(new HitBuilders.AppViewBuilder().build()); // ActionBar actionbar = (ActionBar) findViewById(R.id.actionBar1); // actionbar.addAction(new Action() { // // @Override // public void performAction(View arg0) { // findViewById(R.id.linearLayout2).setVisibility(View.VISIBLE); // webView.setVisibility(View.GONE); // webView.reload(); // } // // @Override // public int getDrawable() { // return R.drawable.refresh; // } // }, 0); webView.requestFocus(View.FOCUS_DOWN); BCBFragmentUtils.addNavigationActions(this); supportInvalidateOptionsMenu(); }
From source file:at.ac.uniklu.mobile.sportal.WebViewActivity.java
@SuppressLint("SetJavaScriptEnabled") @Override//from www .ja va2s. co m protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String targetUrl = getIntent().getStringExtra(URL); if (targetUrl == null || targetUrl.length() == 0) { // if there's no URL, close the activity finish(); } setContentView(R.layout.webview); mActionBar = new ActionBarHelper(this).setupHeader().addActionRefresh(); // set header title or hide header if no title is given String title = getIntent().getStringExtra(TITLE); if (title != null) { ((TextView) findViewById(R.id.view_title)).setText(title); } else { findViewById(R.id.actionbar).setVisibility(View.GONE); } // Moodle 2.0 uses SSO/CAS authentication mSSO = getIntent().getBooleanExtra(SSO, false); // the moodle hack is only needed until Android 2.3 (or maybe 3.x? - not tested) // Android 4.0 has the redirect history entry problem solved if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) { mExecuteMoodleHack = getIntent().getBooleanExtra(MOODLE_HACK, false); } mWebView = (WebView) findViewById(R.id.web_view); //mWebView.setBackgroundColor(Color.BLACK); // black color messes up the CAS login page mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // http://stackoverflow.com/questions/3998916/android-webview-leaves-space-for-scrollbar mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setLightTouchEnabled(true); mWebView.getSettings().setLoadWithOverviewMode(true); mWebView.getSettings().setBuiltInZoomControls(true); mWebView.getSettings().setUseWideViewPort(true); // setup custom webview client that shows a progress dialog while loading mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("https://sso.uni-klu.ac.at") || url.startsWith("https://sso.aau.at") || url.startsWith("https://campus.aau.at") || url.startsWith("https://moodle.aau.at")) { return false; } else if (url.startsWith("http://campus-gis.aau.at/")) { Log.d(TAG, "REDIRECT TO MAP"); String roomParameter = "curRouteTo="; int index = url.indexOf(roomParameter); if (index > -1) { MapUtils.openMapAndShowRoom(WebViewActivity.this, url.substring(index + roomParameter.length())); } return true; } // open external websites in browser Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { progressNotificationOn(); super.onPageStarted(view, url, favicon); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); progressNotificationOff(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); progressNotificationOff(); /* * the first page of moodle opens through a redirect so we need to clear the first history * entry to avoid execution of the redirect when going back through the history with the back button */ if (mExecuteMoodleHack && mWebView.canGoBack()) { mWebView.clearHistory(); mExecuteMoodleHack = false; } else { mIsFirstPage = false; } } }); mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Analytics.onEvent(Analytics.EVENT_WEB_COURSEMOODLE_DOWNLOAD); Uri uri = Uri.parse(url); MoodleDownloadHelper.download(WebViewActivity.this, uri, Utils.getContentDispositionOrUrlFilename(contentDisposition, uri)); } }); // set session cookie // http://stackoverflow.com/questions/1652850/android-webview-cookie-problem // http://android.joao.jp/2010/11/cookiemanager-and-removeallcookie.html if (Studentportal.getSportalClient().isSessionCookieAvailable()) { CookieSyncManager.createInstance(this); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); //cookieManager.removeSessionCookie(); // NOTE when calling this method the cookies get removed after the next setCookie() gets called Cookie sessionCookie = Studentportal.getSportalClient().getSessionCookie(); cookieManager.setCookie(sessionCookie.getDomain(), Utils.cookieHeaderString(sessionCookie)); if (mSSO) { // set SSO/CAS cookie Cookie ssoCookie = Studentportal.getSportalClient().getCookie("CASTGC"); if (ssoCookie != null) { cookieManager.setCookie(ssoCookie.getDomain(), Utils.cookieHeaderString(ssoCookie)); } } CookieSyncManager.getInstance().sync(); } mIsFirstPage = true; mWebView.loadUrl(targetUrl); }
From source file:cn.zhangls.android.weibo.ui.web.WebActivity.java
/** * ?//from ww w . ja va 2 s . c om */ private void initialize() { // Appbar setSupportActionBar(mBinding.acWebToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // ? Title getSupportActionBar().setTitle(""); mWeiboUrl = getIntent().getStringExtra(WEIBO_URL); //SwipeRefreshLayout mBinding.acWebSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mBinding.acWebWebView.reload(); } }); mBinding.acWebSwipeRefresh.setColorSchemeColors(ContextCompat.getColor(this, R.color.colorAccent)); mBinding.acWebWebView.loadUrl(mWeiboUrl); mBinding.acWebWebView.setWebChromeClient(new WebChromeClient() { /** * Tell the host application the current progress of loading a page. * * @param view The WebView that initiated the callback. * @param newProgress Current page loading progress, represented by */ @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { mBinding.acWebSwipeRefresh.setRefreshing(false); } } /** * Notify the host application of a change in the document title. * * @param view The WebView that initiated the callback. * @param title A String containing the new title of the document. */ @Override public void onReceivedTitle(WebView view, String title) { getSupportActionBar().setTitle(title); } }); mBinding.acWebWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { mBinding.acWebWebView.loadUrl(mWeiboUrl); return true; } }); // ??javascript mBinding.acWebWebView.getSettings().setJavaScriptEnabled(true); // mBinding.acWebWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); }
From source file:com.amgems.uwschedule.api.uw.LoginAuthenticator.java
private LoginAuthenticator(Context context, Handler handler, HttpClient httpClient, String username, String password) {// w w w . j a va 2 s . c o m mUsername = username; mPassword = password; mCookiesValue = ""; mHttpClient = httpClient; mLoadingFinished = false; mJsWebview = new WebView(context); mHandler = handler; CookieManager.getInstance().removeAllCookie(); mJsWebview.getSettings().setJavaScriptEnabled(true); mJsWebview.addJavascriptInterface(new CaptureHtmBody(), CaptureHtmBody.INTERFACE_NAME); mJsWebview.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // If the page has been loaded before, then the WebView must have // returned from a JavaScript redirect required for // appropriate login cookies. This is when the html content // should be captured and processed if (mPageLoadCount >= 1) view.loadUrl(CaptureHtmBody.CAPTURE_HTML_SCRIPT); mPageLoadCount++; } }); }
From source file:org.liberty.android.fantastischmemo.downloader.google.GoogleOAuth2AccessCodeRetrievalFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); final View v = inflater.inflate(R.layout.oauth_login_layout, container, false); final WebView webview = (WebView) v.findViewById(R.id.login_page); final View loadingText = v.findViewById(R.id.auth_page_load_text); final View progressDialog = v.findViewById(R.id.auth_page_load_progress); final LinearLayout ll = (LinearLayout) v.findViewById(R.id.ll); // We have to set up the dialog's webview size manually or the webview will be zero size. // This should be a bug of Android. Rect displayRectangle = new Rect(); Window window = mActivity.getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle); ll.setMinimumWidth((int) (displayRectangle.width() * 0.9f)); ll.setMinimumHeight((int) (displayRectangle.height() * 0.8f)); webview.getSettings().setJavaScriptEnabled(true); try {//from w w w .j a v a2 s. c o m String uri = String.format( "https://accounts.google.com/o/oauth2/auth?client_id=%s&response_type=%s&redirect_uri=%s&scope=%s", URLEncoder.encode(AMEnv.GOOGLE_CLIENT_ID, "UTF-8"), URLEncoder.encode("code", "UTF-8"), URLEncoder.encode(AMEnv.GOOGLE_REDIRECT_URI, "UTF-8"), URLEncoder.encode(AMEnv.GDRIVE_SCOPE, "UTF-8")); webview.loadUrl(uri); } catch (Exception e) { throw new RuntimeException(e); } // This is workaround to show input on some android version. webview.requestFocus(View.FOCUS_DOWN); webview.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (!v.hasFocus()) { v.requestFocus(); } break; } return false; } }); webview.setWebViewClient(new WebViewClient() { private boolean authenticated = false; @Override public void onPageFinished(WebView view, String url) { loadingText.setVisibility(View.GONE); progressDialog.setVisibility(View.GONE); webview.setVisibility(View.VISIBLE); if (authenticated == true) { return; } String code = getAuthCodeFromUrl(url); String error = getErrorFromUrl(url); if (error != null) { authCodeReceiveListener.onAuthCodeError(error); authenticated = true; dismiss(); } if (code != null) { authenticated = true; authCodeReceiveListener.onAuthCodeReceived(code); dismiss(); } } }); return v; }
From source file:com.ntsync.android.sync.activities.ShowLicensesActivity.java
private void showPageOfText(String text) { // Create an AlertDialog to display the WebView in. AlertDialog.Builder builder = new AlertDialog.Builder(ShowLicensesActivity.this); builder.setCancelable(true).setView(mWebView).setTitle(R.string.license_activity_title); mTextDlg = builder.create();/*from w w w . j a va 2s . c o m*/ mTextDlg.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dlgi) { ShowLicensesActivity.this.finish(); } }); // Begin the loading. This will be done in a separate thread in WebView. mWebView.loadDataWithBaseURL(null, text, "text/html", "utf-8", null); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { if (mSpinnerDlg != null) { mSpinnerDlg.dismiss(); } if (!ShowLicensesActivity.this.isFinishing()) { mTextDlg.show(); } } }); mWebView = null; }