List of usage examples for android.webkit WebViewClient WebViewClient
WebViewClient
From source file:com.wellsandwhistles.android.redditsp.fragments.WebViewFragment.java
@SuppressLint("NewApi") @Override/*from w ww . j a v a 2s .co m*/ public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { mActivity = (AppCompatActivity) getActivity(); CookieSyncManager.createInstance(mActivity); outer = (FrameLayout) inflater.inflate(R.layout.web_view_fragment, null); webView = (WebViewFixed) outer.findViewById(R.id.web_view_fragment_webviewfixed); final FrameLayout loadingViewFrame = (FrameLayout) outer .findViewById(R.id.web_view_fragment_loadingview_frame); /*handle download links show an alert box to load this outside the internal browser*/ webView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { { new AlertDialog.Builder(mActivity).setTitle(R.string.download_link_title) .setMessage(R.string.download_link_message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); getContext().startActivity(i); mActivity.onBackPressed(); //get back from internal browser } }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.onBackPressed(); //get back from internal browser } }).setIcon(android.R.drawable.ic_dialog_alert).show(); } } }); /*handle download links end*/ progressView = new ProgressBar(mActivity, null, android.R.attr.progressBarStyleHorizontal); loadingViewFrame.addView(progressView); loadingViewFrame.setPadding(General.dpToPixels(mActivity, 10), 0, General.dpToPixels(mActivity, 10), 0); final WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(false); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setDomStorageEnabled(true); settings.setDisplayZoomControls(false); // TODO handle long clicks webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, final int newProgress) { super.onProgressChanged(view, newProgress); General.UI_THREAD_HANDLER.post(new Runnable() { @Override public void run() { progressView.setProgress(newProgress); progressView.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE); } }); } }); if (mUrl != null) { webView.loadUrl(mUrl); } else { webView.loadDataWithBaseURL("https://reddit.com/", html, "text/html; charset=UTF-8", null, null); } webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(final WebView view, final String url) { if (url == null) return false; if (url.startsWith("data:")) { // Prevent imgur bug where we're directed to some random data URI return true; } // Go back if loading same page to prevent redirect loops. if (goingBack && currentUrl != null && url.equals(currentUrl)) { General.quickToast(mActivity, String.format(Locale.US, "Handling redirect loop (level %d)", -lastBackDepthAttempt), Toast.LENGTH_SHORT); lastBackDepthAttempt--; if (webView.canGoBackOrForward(lastBackDepthAttempt)) { webView.goBackOrForward(lastBackDepthAttempt); } else { mActivity.finish(); } } else { if (RedditURLParser.parse(Uri.parse(url)) != null) { LinkHandler.onLinkClicked(mActivity, url, false); } else { webView.loadUrl(url); currentUrl = url; } } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); if (mUrl != null && url != null) { final AppCompatActivity activity = mActivity; if (activity != null) { activity.setTitle(url); } } } @Override public void onPageFinished(final WebView view, final String url) { super.onPageFinished(view, url); new Timer().schedule(new TimerTask() { @Override public void run() { General.UI_THREAD_HANDLER.post(new Runnable() { @Override public void run() { if (currentUrl == null || url == null) return; if (!url.equals(view.getUrl())) return; if (goingBack && url.equals(currentUrl)) { General.quickToast(mActivity, String.format(Locale.US, "Handling redirect loop (level %d)", -lastBackDepthAttempt)); lastBackDepthAttempt--; if (webView.canGoBackOrForward(lastBackDepthAttempt)) { webView.goBackOrForward(lastBackDepthAttempt); } else { mActivity.finish(); } } else { goingBack = false; } } }); } }, 1000); } @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { super.doUpdateVisitedHistory(view, url, isReload); } }); final FrameLayout outerFrame = new FrameLayout(mActivity); outerFrame.addView(outer); return outerFrame; }
From source file:com.example.prasadnr.traquad.TraQuad.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tra_quad); ConnectivityManager connManager = (ConnectivityManager) getSystemService(TraQuad.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); Builder alert = new AlertDialog.Builder(TraQuad.this); WifiManager managerWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); Method[] wmMethods = managerWifi.getClass().getDeclaredMethods(); for (Method method : wmMethods) { if (method.getName().equals("isWifiApEnabled")) { try { isWifiAPenabled = (boolean) method.invoke(managerWifi); } catch (IllegalArgumentException e) { e.printStackTrace();/*from w ww.ja v a 2s .com*/ } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } final ProgressDialog pDialog; MediaController mediaController = new MediaController(this); pDialog = new ProgressDialog(TraQuad.this); pDialog.setTitle("TraQuad app (Connecting...)"); pDialog.setMessage("Buffering...Please wait..."); pDialog.setCancelable(true); if (!isWifiAPenabled) { alert.setTitle("WiFi Hotspot Settings"); alert.setMessage("Can you please connect WiFi-hotspot?"); alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { irritation = true; startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); pDialog.show(); } }); alert.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //Dismiss AlertDialog pDialog.show(); Toast.makeText(getApplicationContext(), "Please connect your WiFi!", Toast.LENGTH_LONG).show(); } }); alert.setCancelable(false); AlertDialog alertDialog = alert.create(); alertDialog.show(); } WebView webView = (WebView) findViewById(R.id.webView); if (irritation == true | isWifiAPenabled) { pDialog.show(); } mediaController.setAnchorView(webView); mediaController.setVisibility(View.GONE); extra = getIntent().getStringExtra("VideosId"); webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setPluginState(WebSettings.PluginState.ON); final GlobalClass globalVariable = (GlobalClass) getApplicationContext(); final String IPaddressNew = globalVariable.getIP(); final String httpString = "http://"; final String commandPort = String.valueOf(1500); final String streamPort = String.valueOf(8080); final String IPaddressStream = httpString + IPaddressNew + ":" + streamPort; final String IPaddressCommand = httpString + IPaddressNew + ":" + commandPort; TextView sendCharacter = (TextView) findViewById(R.id.sendCharacter); try { webView.loadUrl(IPaddressStream); } catch (Exception e) { Toast.makeText(getApplicationContext(), IPaddressNew + ":Error!", Toast.LENGTH_LONG).show(); } webView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { pDialog.dismiss(); } }); final Button switchact = (Button) findViewById(R.id.btn2); switchact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent act1 = new Intent(view.getContext(), Joypad.class); startActivity(act1); } }); final Button hometraquad = (Button) findViewById(R.id.button5); hometraquad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent acthometraquad = new Intent(TraQuad.this, MainActivity.class); startActivity(acthometraquad); } }); }
From source file:com.rsltc.profiledata.main.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button loginButton = (Button) findViewById(R.id.button); loginButton.setOnClickListener(new View.OnClickListener() { @Override/*from www . ja v a 2 s.c om*/ public void onClick(View v) { try { AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity); alert.setTitle("Title here"); StringBuilder query = new StringBuilder(); query.append("redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8")); query.append("&client_id=" + URLEncoder.encode(clientId, "utf-8")); query.append("&scope=" + URLEncoder.encode(scopes, "utf-8")); query.append("&response_type=code"); URI uri = new URI("https://login.live.com/oauth20_authorize.srf?" + query.toString()); URL url = uri.toURL(); final WebView wv = new WebView(thisActivity); WebSettings webSettings = wv.getSettings(); webSettings.setJavaScriptEnabled(true); wv.loadUrl(url.toString()); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String location) { Log.e(TAG, location); // TODO: extract to method try { URL url = new URL(location); if (url.getPath().equalsIgnoreCase("/oauth20_desktop.srf")) { System.out.println("Dit werkt al!"); System.out.println(url.getQuery()); Map<String, List<String>> result = splitQuery(url); if (result.containsKey("code")) { System.out.println("bevat code"); if (result.containsKey("error")) { System.out.println(String.format("{0}\r\n{1}", result.get("error"), result.get("errorDesc"))); } System.out.println(result.get("code").get(0)); String tokenError = GetToken(result.get("code").get(0), false); if (tokenError == null || "".equals(tokenError)) { System.out.println("Successful sign-in!"); Log.e(TAG, "Successful sign-in!"); } else { Log.e(TAG, "tokenError: " + tokenError); } } else { System.out.println("Successful sign-out!"); } } } catch (IOException | URISyntaxException e) { e.printStackTrace(); } view.loadUrl(location); return true; } }); LinearLayout linearLayout = new LinearLayout(thisActivity); linearLayout.setMinimumHeight(500); ArrayList<View> views = new ArrayList<View>(); views.add(wv); linearLayout.addView(wv); EditText text = new EditText(thisActivity); text.setVisibility(View.GONE); linearLayout.addView(text); alert.setView(linearLayout); alert.setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); alert.show(); } catch (Exception e) { Log.e(TAG, "dd"); } } }); Button showProfile = (Button) findViewById(R.id.button2); showProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProfile(); } }); Button showSummmary = (Button) findViewById(R.id.button3); showSummmary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSummaries(); } }); if (savedInstanceState != null) { authInProgress = savedInstanceState.getBoolean(AUTH_PENDING); } buildFitnessClient(); }
From source file:com.example.manan.enhancedurdureader.EpubReader.BookView.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override/*from www . j a va 2s.c o m*/ public void onActivityCreated(Bundle saved) { super.onActivityCreated(saved); view = (WebView) getView().findViewById(R.id.Viewport); view.getSettings().setTextZoom(textSize); mScaleDetector = new ScaleGestureDetector(getActivity().getBaseContext(), new ScaleGestureDetector.OnScaleGestureListener() { @Override public void onScaleEnd(ScaleGestureDetector detector) { } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public boolean onScale(ScaleGestureDetector detector) { //Log.w(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor()); return false; } }); // enable JavaScript for cool things to happen! view.getSettings().setJavaScriptEnabled(true); // ----- SWIPE PAGE view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { /* if (state == ViewStateEnum.books) swipePage(v, event, 0); //int fontSize, newFont;*/ WebView view = (WebView) v; switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: x1 = event.getX(); break; case MotionEvent.ACTION_UP: if (mode != ZOOM && swipeFlag) { //if (state == ViewStateEnum.books) //swipePage(v, event, 0); } break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); if (oldDist > 10f) { mode = ZOOM; } break; case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; case MotionEvent.ACTION_MOVE: if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 10f) { float scale = newDist / oldDist; if (scale > 1) { int currentTextSize = view.getSettings().getTextZoom(); textSize = currentTextSize + 15; view.getSettings().setTextZoom(textSize); mode = NONE; swipeFlag = false; } else { int currentTextSize = view.getSettings().getTextZoom(); textSize = currentTextSize - 15; view.getSettings().setTextZoom(textSize); mode = NONE; swipeFlag = false; } } } break; } return view.onTouchEvent(event); } }); // ----- NOTE & LINK view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { Message msg = new Message(); msg.setTarget(new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); String url = msg.getData().getString(getString(R.string.url)); if (url != null) navigator.setNote(url, index); } }); view.requestFocusNodeHref(msg); return false; } }); view.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { try { navigator.setBookPage(url, index); } catch (Exception e) { errorMessage(getString(R.string.error_LoadPage)); } return true; } }); loadPage(viewedPage); }
From source file:de.storyquest.client.ContentActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // enable immersive mode getWindow().getDecorView()// w w w. j ava2s . c om .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); getWindow().addFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); // load initial layout setContentView(R.layout.activity_content); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); View header = navigationView.getHeaderView(0); // apply theme try { Drawable d = Drawable.createFromStream(getAssets().open("sidebar.jpg"), null); navigationView.setBackground(d); } catch (Exception e) { throw new RuntimeException(e); } // wire the drawer open event to the character sheet refresh DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer != null) { drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); execJavaScriptInCharactersheet("if(typeof refresh!='undefined')refresh()"); } }); } // get extra data with bookmark to load Intent intent = getIntent(); if (intent.hasExtra(BOOKMARKID)) bookmarkId = intent.getStringExtra(BOOKMARKID); // set the cover image from assets ImageView coverImage = (ImageView) header.findViewById(R.id.coverImage); try { InputStream ims = getAssets().open("cover.png"); Drawable d = Drawable.createFromStream(ims, null); coverImage.setImageDrawable(d); } catch (Exception e) { throw new RuntimeException("Error loading cover image. Is 'cover.png' available in assets?", e); } // make the web content debuggable from external chrome tools WebView.setWebContentsDebuggingEnabled(true); // enable script interfaces scriptSystem = new ScriptSystem(this); scriptStorage = new ScriptStorage(this, getApplicationContext().getSharedPreferences(ScriptStorage.CONTEXT, Context.MODE_PRIVATE)); scriptSound = new ScriptSound(this); scriptGameServices = new ScriptGameServices(this); // setup character webview character = (WebView) header.findViewById(R.id.characterView); character.getSettings().setJavaScriptEnabled(true); character.getSettings().setDomStorageEnabled(true); character.getSettings().setAllowFileAccess(true); character.getSettings().setAppCacheEnabled(true); character.addJavascriptInterface(scriptSystem, "sqSystem"); character.addJavascriptInterface(scriptStorage, "nativeStorage"); character.addJavascriptInterface(scriptSound, "sqSound"); character.addJavascriptInterface(scriptGameServices, "sqGameServices"); character.loadUrl("file:///android_asset/character.html"); // setup web view web = (WebView) findViewById(R.id.webView); web.getSettings().setJavaScriptEnabled(true); web.getSettings().setDomStorageEnabled(true); web.getSettings().setAllowFileAccess(true); web.getSettings().setAppCacheEnabled(true); web.addJavascriptInterface(scriptSystem, "sqSystem"); web.addJavascriptInterface(scriptStorage, "nativeStorage"); web.addJavascriptInterface(scriptSound, "sqSound"); web.addJavascriptInterface(scriptGameServices, "sqGameServices"); // adding event overrides for the web view web.setWebChromeClient(new WebChromeClient()); web.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String urlText) { if (urlText.startsWith("http")) { // Could be cleverer and use a regex Log.d(LOGTAG, "Opening standard web intent window for " + urlText); Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(urlText)); startActivity(i); return true; } else { Log.d(LOGTAG, "Loading in webview: " + urlText); web.loadUrl(urlText); return true; } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.d(LOGTAG, "Page rendering started: " + url + "."); displaySpinner(R.string.loading); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { Log.d(LOGTAG, "Page rendering finished: " + url + "."); hideSpinner(); if (bookmarkId != null && url.startsWith("file:///android_asset/content.html")) { Log.i(LOGTAG, "Loading bookmark " + bookmarkId + "."); execJavaScriptInContent("loadBookmark('" + bookmarkId + "')"); bookmarkId = null; } super.onPageFinished(view, url); } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { Log.d(LOGTAG, "Intercepted call: " + url + "."); return null; } }); web.setWebChromeClient(new WebChromeClient() { public boolean onConsoleMessage(ConsoleMessage cm) { Log.d(LOGTAG, cm.message() + " - from line " + cm.lineNumber() + " of " + cm.sourceId()); return true; } }); web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH); web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); web.requestFocus(View.FOCUS_DOWN); // finally loading content bootstrap Log.i(LOGTAG, "Loading index.html"); web.loadUrl("file:///android_asset/index.html"); }
From source file:aarddict.android.ArticleViewActivity.java
@Override void initUI() {/*ww w . j a v a 2 s. c om*/ this.scrollPositionsH = Collections.synchronizedMap(new HashMap<Article, ScrollXY>()); this.scrollPositionsV = Collections.synchronizedMap(new HashMap<Article, ScrollXY>()); loadAssets(); if (DeviceInfo.EINK_SCREEN) { useAnimation = false; setContentView(R.layout.eink_article_view); articleView = (ArticleView) findViewById(R.id.EinkArticleView); N2EpdController.n2MainActivity = this; EinkScreen.ResetController(2, articleView); // force full screen // refresh when changing // articles } // Setup animations only on non-eink screens else { useAnimation = true; fadeOutAnimation = new AlphaAnimation(1f, 0f); fadeOutAnimation.setDuration(600); fadeOutAnimation.setAnimationListener(new AnimationAdapter() { public void onAnimationEnd(Animation animation) { Button nextButton = (Button) findViewById(R.id.NextButton); nextButton.setVisibility(Button.GONE); } }); getWindow().requestFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.article_view); articleView = (ArticleView) findViewById(R.id.ArticleView); } timer = new Timer(); backItems = Collections.synchronizedList(new LinkedList<HistoryItem>()); if (android.os.Build.VERSION.SDK_INT >= 11) { try { showFindDialogMethod = articleView.getClass().getMethod("showFindDialog", String.class, boolean.class); } catch (NoSuchMethodException e1) { Log.d(TAG, "showFindDialog method not found"); } } articleView.setOnScrollListener(new ArticleView.ScrollListener() { public void onScroll(int l, int t, int oldl, int oldt) { saveScrollPos(l, t); } }); articleView.getSettings().setJavaScriptEnabled(true); articleView.addJavascriptInterface(new SectionMatcher(), "matcher"); articleView.addJavascriptInterface(articleView, "scrollControl"); articleView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(TAG + ".js", String.format("[%s]: %s", url, message)); result.cancel(); return true; } public void onProgressChanged(WebView view, int newProgress) { Log.d(TAG, "Progress: " + newProgress); setProgress(5000 + newProgress * 50); } }); articleView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { Log.d(TAG, "Page finished: " + url); currentTask = null; String section = null; if (url.contains("#")) { LookupWord lookupWord = LookupWord.splitWord(url); section = lookupWord.section; if (backItems.size() > 0) { HistoryItem currentHistoryItem = backItems.get(backItems.size() - 1); HistoryItem h = new HistoryItem(currentHistoryItem); h.article.section = section; backItems.add(h); } } else if (backItems.size() > 0) { Article current = backItems.get(backItems.size() - 1).article; section = current.section; } if (!restoreScrollPos()) { goToSection(section); } updateNextButtonVisibility(); } @Override public boolean shouldOverrideUrlLoading(WebView view, final String url) { Log.d(TAG, "URL clicked: " + url); String urlLower = url.toLowerCase(); if (urlLower.startsWith("http://") || urlLower.startsWith("https://") || urlLower.startsWith("ftp://") || urlLower.startsWith("sftp://") || urlLower.startsWith("mailto:")) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); } else { if (currentTask == null) { currentTask = new TimerTask() { public void run() { try { Article currentArticle = backItems.get(backItems.size() - 1).article; try { Iterator<Entry> currentIterator = dictionaryService.followLink(url, currentArticle.volumeId); List<Entry> result = new ArrayList<Entry>(); while (currentIterator.hasNext() && result.size() < 20) { result.add(currentIterator.next()); } showNext(new HistoryItem(result)); } catch (ArticleNotFound e) { showMessage(getString(R.string.msgArticleNotFound, e.word.toString())); } } catch (Exception e) { StringBuilder msgBuilder = new StringBuilder( "There was an error following link ").append("\"").append(url) .append("\""); if (e.getMessage() != null) { msgBuilder.append(": ").append(e.getMessage()); } final String msg = msgBuilder.toString(); Log.e(TAG, msg, e); showError(msg); } } }; try { timer.schedule(currentTask, 0); } catch (Exception e) { Log.d(TAG, "Failed to schedule task", e); } } } return true; } }); final Button nextButton = (Button) findViewById(R.id.NextButton); nextButton.getBackground().setAlpha(180); nextButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (nextButton.getVisibility() == View.VISIBLE) { updateNextButtonVisibility(); nextArticle(); updateNextButtonVisibility(); } } }); articleView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { updateNextButtonVisibility(); return false; } }); setProgressBarVisibility(true); }
From source file:com.irccloud.android.activity.PastebinViewerActivity.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override//ww w. j a v a 2s.c o m protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(ColorScheme.getDialogWhenLargeTheme(ColorScheme.getUserTheme())); onMultiWindowModeChanged(isMultiWindow()); if (savedInstanceState == null && (getWindowManager().getDefaultDisplay().getWidth() < TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 800, getResources().getDisplayMetrics()) || isMultiWindow())) overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out); setContentView(R.layout.activity_pastebin); mSpinner = findViewById(R.id.spinner); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setNavigationIcon(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_material); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); getSupportActionBar().setTitle(""); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mWebView = findViewById(R.id.image); mWebView.setBackgroundColor(ColorScheme.getInstance().contentBackgroundColor); mWebView.getSettings().setBuiltInZoomControls(true); if (Integer.parseInt(Build.VERSION.SDK) >= 19) mWebView.getSettings() .setDisplayZoomControls(!getPackageManager().hasSystemFeature("android.hardware.touchscreen")); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new JSInterface(), "Android"); mWebView.getSettings().setLoadWithOverviewMode(false); mWebView.getSettings().setUseWideViewPort(false); mWebView.getSettings().setAppCacheEnabled(false); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { fail(); } @Override public void onLoadResource(WebView view, String url) { } }); mWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { Crashlytics.log( consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR ? Log.ERROR : Log.WARN, "IRCCloud", "Javascript error - line: " + consoleMessage.lineNumber() + " message: " + consoleMessage.message()); return super.onConsoleMessage(consoleMessage); } }); if (savedInstanceState != null && savedInstanceState.containsKey("url")) { url = savedInstanceState.getString("url"); html = savedInstanceState.getString("html"); mWebView.loadDataWithBaseURL(url, html, "text/html", "UTF-8", null); } else { if (getIntent() != null && getIntent().getDataString() != null) { url = getIntent().getDataString().replace(getResources().getString(R.string.PASTE_SCHEME), "https"); if (!url.contains("?")) url += "?"; try { url += "&mobile=android&version=" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName + "&theme=" + ColorScheme.getUserTheme(); } catch (PackageManager.NameNotFoundException e) { } new FetchPastebinTask().execute(); Answers.getInstance().logContentView(new ContentViewEvent().putContentType("Pastebin")); } else { finish(); } } }
From source file:com.mario22gmail.license.nfc_project.FragmentBrowser.java
public void OpenWebSite(String urlFromCredential, String javaScript) { mWebview.loadUrl(urlFromCredential); WebSettings settings = mWebview.getSettings(); settings.setJavaScriptEnabled(true); urlEditText.setText(urlFromCredential); final String javaScriptFinal = javaScript; final String urlFromCredentialFinal = urlFromCredential; mWebview.setWebViewClient(new WebViewClient() { @Override/*from w w w . j a v a2 s .c om*/ public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (url.startsWith(urlFromCredentialFinal)) { if (Build.VERSION.SDK_INT >= 19) { view.evaluateJavascript(javaScriptFinal, new ValueCallback<String>() { @Override public void onReceiveValue(String s) { } }); } else { view.loadUrl(javaScriptFinal); } } } }); }
From source file:net.oremland.rss.reader.fragments.BrowserFragment.java
protected WebViewClient getWebViewClient() { return new WebViewClient() { @Override/*from w ww .ja v a 2s .c om*/ public void onPageStarted(WebView view, String url, Bitmap favicon) { updateProgressBarVisibility(true); } @Override public void onPageFinished(WebView view, String url) { updateProgressBarVisibility(false); } }; }
From source file:com.azure.webapi.LoginManager.java
/** * Creates the UI for the interactive authentication process * //w ww.j a v a 2s .co m * @param provider * The provider used for the authentication process * @param startUrl * The initial URL for the authentication process * @param endUrl * The final URL for the authentication process * @param context * The context used to create the authentication dialog * @param callback * Callback to invoke when the authentication process finishes */ protected void showLoginUI(MobileServiceAuthenticationProvider provider, final String startUrl, final String endUrl, final Context context, LoginUIOperationCallback callback) { if (startUrl == null || startUrl == "") { throw new IllegalArgumentException("startUrl can not be null or empty"); } if (endUrl == null || endUrl == "") { throw new IllegalArgumentException("endUrl can not be null or empty"); } if (context == null) { throw new IllegalArgumentException("context can not be null"); } final LoginUIOperationCallback externalCallback = callback; final AlertDialog.Builder builder = new AlertDialog.Builder(context); // Create the Web View to show the login page final WebView wv = new WebView(context); builder.setTitle("Connecting to a service"); builder.setCancelable(true); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (externalCallback != null) { externalCallback.onCompleted(null, new MobileServiceException("User Canceled")); } } }); // Set cancel button's action builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (externalCallback != null) { externalCallback.onCompleted(null, new MobileServiceException("User Canceled")); } wv.destroy(); } }); wv.getSettings().setJavaScriptEnabled(true); wv.requestFocus(View.FOCUS_DOWN); wv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) { if (!view.hasFocus()) { view.requestFocus(); } } return false; } }); // Create a LinearLayout and add the WebView to the Layout LinearLayout layout = new LinearLayout(context); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(wv); // Add a dummy EditText to the layout as a workaround for a bug // that prevents showing the keyboard for the WebView on some devices EditText dummyEditText = new EditText(context); dummyEditText.setVisibility(View.GONE); layout.addView(dummyEditText); // Add the layout to the dialog builder.setView(layout); final AlertDialog dialog = builder.create(); wv.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // If the URL of the started page matches with the final URL // format, the login process finished if (isFinalUrl(url)) { if (externalCallback != null) { externalCallback.onCompleted(url, null); } dialog.dismiss(); } super.onPageStarted(view, url, favicon); } // Checks if the given URL matches with the final URL's format private boolean isFinalUrl(String url) { if (url == null) { return false; } return url.startsWith(endUrl); } // Checks if the given URL matches with the start URL's format private boolean isStartUrl(String url) { if (url == null) { return false; } return url.startsWith(startUrl); } @Override public void onPageFinished(WebView view, String url) { if (isStartUrl(url)) { if (externalCallback != null) { externalCallback.onCompleted(null, new MobileServiceException( "Logging in with the selected authentication provider is not enabled")); } dialog.dismiss(); } } }); wv.loadUrl(startUrl); dialog.show(); }