List of usage examples for android.webkit WebSettings LOAD_DEFAULT
int LOAD_DEFAULT
To view the source code for android.webkit WebSettings LOAD_DEFAULT.
Click Source Link
From source file:de.baumann.browser.Browser.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView.enableSlowWholeDocumentDraw(); setContentView(R.layout.activity_browser); helper_main.onStart(Browser.this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);/*from www .ja v a 2 s. com*/ PreferenceManager.setDefaultValues(this, R.xml.user_settings, false); PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); sharedPref.edit().putInt("keyboard", 0).apply(); sharedPref.getInt("keyboard", 0); customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer); progressBar = (ProgressBar) findViewById(R.id.progressBar); editText = (EditText) findViewById(R.id.editText); editText.setHint(R.string.app_search_hint); editText.clearFocus(); imageButton = (ImageButton) findViewById(R.id.imageButton); imageButton.setVisibility(View.INVISIBLE); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWebView.scrollTo(0, 0); imageButton.setVisibility(View.INVISIBLE); actionBar = getSupportActionBar(); assert actionBar != null; if (!actionBar.isShowing()) { editText.setText(mWebView.getTitle()); actionBar.show(); } setNavArrows(); } }); SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe); assert swipeView != null; swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent); swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mWebView.reload(); } }); mWebView = (ObservableWebView) findViewById(R.id.webView); if (sharedPref.getString("fullscreen", "2").equals("2") || sharedPref.getString("fullscreen", "2").equals("3")) { mWebView.setScrollViewCallbacks(this); } mWebChromeClient = new myWebChromeClient(); mWebView.setWebChromeClient(mWebChromeClient); imageButton_left = (ImageButton) findViewById(R.id.imageButton_left); imageButton_right = (ImageButton) findViewById(R.id.imageButton_right); if (sharedPref.getBoolean("arrow", false)) { imageButton_left.setVisibility(View.VISIBLE); imageButton_right.setVisibility(View.VISIBLE); } else { imageButton_left.setVisibility(View.INVISIBLE); imageButton_right.setVisibility(View.INVISIBLE); } helper_webView.webView_Settings(Browser.this, mWebView); helper_webView.webView_WebViewClient(Browser.this, swipeView, mWebView, editText); mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); if (isNetworkUnAvailable()) { if (sharedPref.getBoolean("offline", false)) { if (isNetworkUnAvailable()) { // loading offline mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show(); } } else { Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show(); } } mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimetype, long contentLength) { registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); Snackbar snackbar = Snackbar .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG) .setAction(getString(R.string.toast_yes), new View.OnClickListener() { @Override public void onClick(View view) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url)); request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed! request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(request); Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename, Snackbar.LENGTH_SHORT).show(); } }); snackbar.show(); } }); helper_editText.editText_Touch(editText, Browser.this, mWebView); helper_editText.editText_EditorAction(editText, Browser.this, mWebView); helper_editText.editText_FocusChange(editText, Browser.this); onNewIntent(getIntent()); helper_main.grantPermissionsStorage(Browser.this); }
From source file:de.baumann.browser.Browser_right.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwoDark)); WebView.enableSlowWholeDocumentDraw(); setContentView(R.layout.activity_browser); helper_main.onStart(Browser_right.this); PreferenceManager.setDefaultValues(this, R.xml.user_settings, false); PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); sharedPref.edit()/*from w w w. java 2s. c o m*/ .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/")) .apply(); sharedPref.edit().putInt("keyboard", 0).apply(); sharedPref.getInt("keyboard", 0); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setBackgroundColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwo)); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer); progressBar = (ProgressBar) findViewById(R.id.progressBar); editText = (EditText) findViewById(R.id.editText); editText.setVisibility(View.GONE); editText.setHint(R.string.app_search_hint); editText.clearFocus(); urlBar = (TextView) findViewById(R.id.urlBar); imageButton = (ImageButton) findViewById(R.id.imageButton); imageButton.setVisibility(View.INVISIBLE); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWebView.scrollTo(0, 0); imageButton.setVisibility(View.INVISIBLE); if (!actionBar.isShowing()) { urlBar.setText(mWebView.getTitle()); actionBar.show(); } helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right); } }); SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe); assert swipeView != null; swipeView.setColorSchemeResources(R.color.colorTwo, R.color.colorAccent); swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mWebView.reload(); } }); mWebView = (ObservableWebView) findViewById(R.id.webView); if (sharedPref.getString("fullscreen", "2").equals("2") || sharedPref.getString("fullscreen", "2").equals("3")) { mWebView.setScrollViewCallbacks(this); } mWebChromeClient = new myWebChromeClient(); mWebView.setWebChromeClient(mWebChromeClient); imageButton_left = (ImageButton) findViewById(R.id.imageButton_left); imageButton_right = (ImageButton) findViewById(R.id.imageButton_right); if (sharedPref.getBoolean("arrow", false)) { imageButton_left.setVisibility(View.VISIBLE); imageButton_right.setVisibility(View.VISIBLE); } else { imageButton_left.setVisibility(View.INVISIBLE); imageButton_right.setVisibility(View.INVISIBLE); } helper_webView.webView_Settings(Browser_right.this, mWebView); helper_webView.webView_WebViewClient(Browser_right.this, swipeView, mWebView, urlBar); mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); if (isNetworkUnAvailable()) { if (sharedPref.getBoolean("offline", false)) { if (isNetworkUnAvailable()) { // loading offline mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show(); } } else { Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show(); } } mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimetype, long contentLength) { registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); Snackbar snackbar = Snackbar .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG) .setAction(getString(R.string.toast_yes), new View.OnClickListener() { @Override public void onClick(View view) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url)); request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed! request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(request); Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename, Snackbar.LENGTH_SHORT).show(); } }); snackbar.show(); } }); helper_browser.toolbar(Browser_right.this, Browser_left.class, mWebView, toolbar); helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar); helper_editText.editText_FocusChange(editText, Browser_right.this); helper_main.grantPermissionsStorage(Browser_right.this); onNewIntent(getIntent()); }
From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java
@Override public void create() { try {/* w w w. java2 s .c o m*/ setContentView(R.layout.romanblack_html_main); root = (FrameLayout) findViewById(R.id.romanblack_root_layout); webView = new ObservableWebView(this); webView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); root.addView(webView); webView.setHorizontalScrollBarEnabled(false); setTitle("HTML"); Intent currentIntent = getIntent(); Bundle store = currentIntent.getExtras(); widget = (Widget) store.getSerializable("Widget"); if (widget == null) { handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100); return; } appName = widget.getAppName(); if (widget.getPluginXmlData().length() == 0) { if (currentIntent.getStringExtra("WidgetFile").length() == 0) { handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100); return; } } if (widget.getTitle() != null && widget.getTitle().length() > 0) { setTopBarTitle(widget.getTitle()); } else { setTopBarTitle(getResources().getString(R.string.romanblack_html_web)); } currentUrl = (String) getSession(); if (currentUrl == null) { currentUrl = ""; } ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.isConnectedOrConnecting()) { isOnline = true; } // topbar initialization setTopBarLeftButtonText(getString(R.string.common_home_upper), true, new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); if (isOnline) { webView.getSettings().setJavaScriptEnabled(true); } webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.getSettings().setGeolocationEnabled(true); webView.getSettings().setAllowFileAccess(true); webView.getSettings().setAppCacheEnabled(true); webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setUseWideViewPort(false); webView.getSettings().setSavePassword(false); webView.clearHistory(); webView.invalidate(); if (Build.VERSION.SDK_INT >= 19) { } webView.getSettings().setUserAgentString( "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"); webView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { v.invalidate(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { } break; case MotionEvent.ACTION_UP: { if (!v.hasFocus()) { v.requestFocus(); } } break; case MotionEvent.ACTION_MOVE: { } break; } return false; } }); webView.setBackgroundColor(Color.WHITE); try { if (widget.getBackgroundColor() != Color.TRANSPARENT) { webView.setBackgroundColor(widget.getBackgroundColor()); } } catch (IllegalArgumentException e) { } webView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } }); webView.setWebChromeClient(new WebChromeClient() { FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); @Override public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) { AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this); builder.setTitle(R.string.location_dialog_title); builder.setMessage(R.string.location_dialog_description); builder.setCancelable(true); builder.setPositiveButton(R.string.location_dialog_allow, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { callback.invoke(origin, true, false); } }); builder.setNegativeButton(R.string.location_dialog_not_allow, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { callback.invoke(origin, false, false); } }); AlertDialog alert = builder.create(); alert.show(); } @Override public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { if (customView != null) { customViewCallback.onCustomViewHidden(); return; } view.setBackgroundColor(Color.BLACK); view.setLayoutParams(LayoutParameters); root.addView(view); customView = view; customViewCallback = callback; webView.setVisibility(View.GONE); } @Override public void onHideCustomView() { if (customView == null) { return; } else { closeFullScreenVideo(); } } public void openFileChooser(ValueCallback<Uri> uploadMsg) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT);//Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); isMedia = true; startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); } // For Android 3.0+ public void openFileChooser(ValueCallback uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE); } //For Android 4.1 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); isMedia = true; i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); } @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { isV21 = true; mUploadMessageV21 = filePathCallback; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); return true; } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { super.onReceivedTouchIconUrl(view, url, precomposed); } }); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); if (state == states.EMPTY) { currentUrl = url; setSession(currentUrl); state = states.LOAD_START; handler.sendEmptyMessage(SHOW_PROGRESS); } } @Override public void onLoadResource(WebView view, String url) { if (!alreadyLoaded && (url.startsWith("http://www.youtube.com/get_video_info?") || url.startsWith("https://www.youtube.com/get_video_info?")) && Build.VERSION.SDK_INT < 11) { try { String path = url.contains("https://www.youtube.com/get_video_info?") ? url.replace("https://www.youtube.com/get_video_info?", "") : url.replace("http://www.youtube.com/get_video_info?", ""); String[] parqamValuePairs = path.split("&"); String videoId = null; for (String pair : parqamValuePairs) { if (pair.startsWith("video_id")) { videoId = pair.split("=")[1]; break; } } if (videoId != null) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")) .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId))); needRefresh = true; alreadyLoaded = !alreadyLoaded; return; } } catch (Exception ex) { } } else { super.onLoadResource(view, url); } } @Override public void onPageFinished(WebView view, String url) { if (hideProgress) { if (TextUtils.isEmpty(WebPlugin.this.url)) { state = states.LOAD_COMPLETE; handler.sendEmptyMessage(HIDE_PROGRESS); super.onPageFinished(view, url); } else { view.loadUrl("javascript:(function(){" + "l=document.getElementById('link');" + "e=document.createEvent('HTMLEvents');" + "e.initEvent('click',true,true);" + "l.dispatchEvent(e);" + "})()"); hideProgress = false; } } else { state = states.LOAD_COMPLETE; handler.sendEmptyMessage(HIDE_PROGRESS); super.onPageFinished(view, url); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { if (errorCode == WebViewClient.ERROR_BAD_URL) { startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), DOWNLOAD_REQUEST_CODE); } } @Override public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) { final AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this); builder.setMessage(R.string.notification_error_ssl_cert_invalid); builder.setPositiveButton(WebPlugin.this.getResources().getString(R.string.wp_continue), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handler.proceed(); } }); builder.setNegativeButton(WebPlugin.this.getResources().getString(R.string.wp_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { handler.cancel(); } }); final AlertDialog dialog = builder.create(); dialog.show(); } @Override public void onFormResubmission(WebView view, Message dontResend, Message resend) { super.onFormResubmission(view, dontResend, resend); } @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return super.shouldInterceptRequest(view, request); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { try { if (url.contains("youtube.com/watch")) { if (Build.VERSION.SDK_INT < 11) { try { startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")) .setData(Uri.parse(url))); return true; } catch (Exception ex) { return false; } } else { return false; } } else if (url.contains("paypal.com")) { if (url.contains("&bn=ibuildapp_SP")) { return false; } else { url = url + "&bn=ibuildapp_SP"; webView.loadUrl(url); return true; } } else if (url.contains("sms:")) { try { Intent smsIntent = new Intent(Intent.ACTION_VIEW); smsIntent.setData(Uri.parse(url)); startActivity(smsIntent); return true; } catch (Exception ex) { Log.e("", ex.getMessage()); return false; } } else if (url.contains("tel:")) { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse(url)); startActivity(callIntent); return true; } else if (url.contains("mailto:")) { MailTo mailTo = MailTo.parse(url); Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { mailTo.getTo() }); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mailTo.getSubject()); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mailTo.getBody()); WebPlugin.this.startActivity(Intent.createChooser(emailIntent, getString(R.string.romanblack_html_send_email))); return true; } else if (url.contains("rtsp:")) { Uri address = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, address); final PackageManager pm = getPackageManager(); final List<ResolveInfo> matches = pm.queryIntentActivities(intent, 0); if (matches.size() > 0) { startActivity(intent); } else { Toast.makeText(WebPlugin.this, getString(R.string.romanblack_html_no_video_player), Toast.LENGTH_SHORT).show(); } return true; } else if (url.startsWith("intent:") || url.startsWith("market:") || url.startsWith("col-g2m-2:")) { Intent it = new Intent(); it.setData(Uri.parse(url)); startActivity(it); return true; } else if (url.contains("//play.google.com/")) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } else { if (url.contains("ibuildapp.com-1915109")) { String param = Uri.parse(url).getQueryParameter("widget"); finish(); if (param != null && param.equals("1001")) com.appbuilder.sdk.android.Statics.launchMain(); else if (param != null && !"".equals(param)) { View.OnClickListener widget = Statics.linkWidgets.get(Integer.valueOf(param)); if (widget != null) widget.onClick(view); } return false; } currentUrl = url; setSession(currentUrl); if (!isOnline) { handler.sendEmptyMessage(HIDE_PROGRESS); handler.sendEmptyMessage(STOP_LOADING); } else { String pageType = "application/html"; if (!url.contains("vk.com")) { getPageType(url); } if (pageType.contains("application") && !pageType.contains("html") && !pageType.contains("xml")) { startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), DOWNLOAD_REQUEST_CODE); return super.shouldOverrideUrlLoading(view, url); } else { view.getSettings().setLoadWithOverviewMode(true); view.getSettings().setUseWideViewPort(true); view.setBackgroundColor(Color.WHITE); } } return false; } } catch (Exception ex) { // Error Logging return false; } } }); handler.sendEmptyMessage(SHOW_PROGRESS); new Thread() { @Override public void run() { EntityParser parser; if (widget.getPluginXmlData() != null) { if (widget.getPluginXmlData().length() > 0) { parser = new EntityParser(widget.getPluginXmlData()); } else { String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile")); parser = new EntityParser(xmlData); } } else { String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile")); parser = new EntityParser(xmlData); } parser.parse(); url = parser.getUrl(); html = parser.getHtml(); if (url.length() > 0 && !isOnline) { handler.sendEmptyMessage(NEED_INTERNET_CONNECTION); } else { if (isOnline) { } else { if (html.length() == 0) { } } if (html.length() > 0 || url.length() > 0) { handler.sendEmptyMessageDelayed(SHOW_HTML, 700); } else { handler.sendEmptyMessage(HIDE_PROGRESS); handler.sendEmptyMessage(INITIALIZATION_FAILED); } } } }.start(); } catch (Exception ex) { } }
From source file:org.safegees.safegees.gui.view.MainActivity.java
private void start() { if (DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)).length() > 0) { shareDataWithServer();/*from w w w.ja va2 s .c o m*/ } else { /* TEST if(DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)).length()>0){ launchMainActivity(); }else{ //Start the loggin for result Intent loginInt = new Intent(this, LoginActivity.class); startActivityForResult(loginInt, 1); }*/ if (Connectivity.isNetworkAvaiable(this) || StoredDataQuequesManager.getAppUsersMap(this).size() != 0) { final MainActivity mainActivity = this; //Download data this.adviceUser.setText(getResources().getString(R.string.splash_advice_download_info_hub)); //Test //Not here at final final WebView webView = (WebView) this.findViewById(R.id.webview_info_pre_cache); final ArrayList<String> infoWebUrls = WebViewInfoWebDownloadController.getInfoUrlsArrayList(); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { if (infoWebUrls.size() > 0) { String nextUrl = infoWebUrls.get(0); infoWebUrls.remove(nextUrl); webView.loadUrl(nextUrl); } else { //Only one time DATA_STORAGE.putBoolean(mainActivity.getResources().getString(R.string.KEY_INFO_WEB), true); //Start the loggin for result Intent loginInt = new Intent(mainActivity, LoginActivity.class); startActivityForResult(loginInt, 1); } } }); String nextUrl = infoWebUrls.get(0); infoWebUrls.remove(nextUrl); webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient()); if (StoredDataQuequesManager.getAppUsersMap(mainActivity).size() == 0 && !DATA_STORAGE.getBoolean(getResources().getString(R.string.KEY_INFO_WEB))) { webView.loadUrl(nextUrl); } else { if (DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) .length() > 0) { launchMainActivity(); } else { //Start the loggin for result Intent loginInt = new Intent(mainActivity, LoginActivity.class); startActivityForResult(loginInt, 1); } } } else { setNoInternetAdvice(this); } } }
From source file:com.company.millenium.iwannask.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //GPS/*from w w w .ja v a 2 s. co m*/ locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { public void onLocationChanged(Location location) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(this); } } public void onStatusChanged(String string, int integer, Bundle bundle) { } public void onProviderEnabled(String string) { } public void onProviderDisabled(String string) { } }; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener); } int delay = 30000; // delay for 30 sec. int period = 3000000; // repeat every 5.3min. Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Check Permissions Now final int REQUEST_LOCATION = 2; if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Display UI and wait for user interaction } else { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION); } } else { locationManager.removeUpdates(locationListener); } } }, delay, period); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); Intent mIntent = getIntent(); URL = Constants.SERVER_URL; if (mIntent.hasExtra("url")) { myWebView = null; startActivity(getIntent()); String url = mIntent.getStringExtra("url"); URL = Constants.SERVER_URL + url; } CookieSyncManager.createInstance(this); CookieSyncManager.getInstance().startSync(); myWebView = (WebView) findViewById(R.id.webview); myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath()); myWebView.getSettings().setGeolocationEnabled(true); WebSettings webSettings = myWebView.getSettings(); webSettings.setUseWideViewPort(false); if (!DetectConnection.checkInternetConnection(this)) { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); showNoConnectionDialog(this); } else { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } webSettings.setJavaScriptEnabled(true); myWebView.addJavascriptInterface(new webappinterface(this), "android"); webSettings.setLoadWithOverviewMode(true); webSettings.setUseWideViewPort(true); myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER); //location test webSettings.setAppCacheEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setDomStorageEnabled(true); myWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { CookieSyncManager.getInstance().sync(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); // Ignore SSL certificate errors } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals(Constants.HOST) || Uri.parse(url).getHost().equals(Constants.WWWHOST)) { // This is my web site, so do not override; let my WebView load // the page return false; } // 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)); startActivity(intent); return true; } }); myWebView.setWebChromeClient(new WebChromeClient() { public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } @Override public void onPermissionRequest(final PermissionRequest request) { Log.d(TAG, "onPermissionRequest"); runOnUiThread(new Runnable() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void run() { if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) { request.grant(request.getResources()); } else { request.deny(); } } }); } public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { // Double check that we don't have any existing callbacks if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(null); } mFilePathCallback = filePathCallback; // Set up the take picture intent 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 Log.e(TAG, "Unable to create Image File", ex); } // 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; } } // Set up the intent to get an existing image Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("image/*"); // Set up the intents for the Intent chooser 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; } }); // setContentView(myWebView); // myWebView.loadUrl(URL); myWebView.loadUrl(URL); mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // mRegistrationProgressBar.setVisibility(ProgressBar.GONE); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false); } }; //CookieManager mCookieManager = CookieManager.getInstance(); //Boolean hasCookies = mCookieManager.hasCookies(); //while(!hasCookies); if (checkPlayServices()) { // Start IntentService to register this application with GCM. Intent intent = new Intent(this, RegistrationIntentService.class); //intent.putExtra("session", session); startService(intent); } Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true); if (isFirstRun) { //show start activity startActivity(new Intent(MainActivity.this, MyIntro.class)); } //if (!isOnline()) // showNoConnectionDialog(this); getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit(); //Pull-to-refresh mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container); mSwipeRefreshLayout.setOnRefreshListener(this); }
From source file:de.baumann.browser.Browser_left.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(ContextCompat.getColor(Browser_left.this, R.color.colorPrimaryDark)); WebView.enableSlowWholeDocumentDraw(); setContentView(R.layout.activity_browser); helper_main.checkPin(Browser_left.this); helper_main.onStart(Browser_left.this); PreferenceManager.setDefaultValues(this, R.xml.user_settings, false); PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); sharedPref.edit().putBoolean("isOpened", true).apply(); boolean show = sharedPref.getBoolean("introShowDo_notShow", true); if (show) {/*from w w w . ja v a2s . co m*/ helper_main.switchToActivity(Browser_left.this, Activity_intro.class, "", false); } sharedPref.edit() .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/")) .apply(); sharedPref.edit().putInt("keyboard", 0).apply(); sharedPref.getInt("keyboard", 0); if (sharedPref.getString("saved_key_ok", "no").equals("no")) { char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!$%&/()=?;:_-.,+#*<>" .toCharArray(); StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 25; i++) { char c = chars[random.nextInt(chars.length)]; sb.append(c); } sharedPref.edit().putString("saved_key", sb.toString()).apply(); sharedPref.edit().putString("saved_key_ok", "yes").apply(); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer); progressBar = (ProgressBar) findViewById(R.id.progressBar); editText = (EditText) findViewById(R.id.editText); editText.setVisibility(View.GONE); editText.setHint(R.string.app_search_hint); editText.clearFocus(); urlBar = (TextView) findViewById(R.id.urlBar); imageButton = (ImageButton) findViewById(R.id.imageButton); imageButton.setVisibility(View.INVISIBLE); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWebView.scrollTo(0, 0); imageButton.setVisibility(View.INVISIBLE); if (!actionBar.isShowing()) { urlBar.setText(mWebView.getTitle()); actionBar.show(); } helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right); } }); SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe); assert swipeView != null; swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent); swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mWebView.reload(); } }); mWebView = (ObservableWebView) findViewById(R.id.webView); if (sharedPref.getString("fullscreen", "2").equals("2") || sharedPref.getString("fullscreen", "2").equals("3")) { mWebView.setScrollViewCallbacks(this); } mWebChromeClient = new myWebChromeClient(); mWebView.setWebChromeClient(mWebChromeClient); imageButton_left = (ImageButton) findViewById(R.id.imageButton_left); imageButton_right = (ImageButton) findViewById(R.id.imageButton_right); if (sharedPref.getBoolean("arrow", false)) { imageButton_left.setVisibility(View.VISIBLE); imageButton_right.setVisibility(View.VISIBLE); } else { imageButton_left.setVisibility(View.INVISIBLE); imageButton_right.setVisibility(View.INVISIBLE); } helper_webView.webView_Settings(Browser_left.this, mWebView); helper_webView.webView_WebViewClient(Browser_left.this, swipeView, mWebView, urlBar); mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); if (isNetworkUnAvailable()) { if (sharedPref.getBoolean("offline", false)) { if (isNetworkUnAvailable()) { // loading offline mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show(); } } else { Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show(); } } mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(final String url, String userAgent, final String contentDisposition, final String mimetype, long contentLength) { registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); Snackbar snackbar = Snackbar .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG) .setAction(getString(R.string.toast_yes), new View.OnClickListener() { @Override public void onClick(View view) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url)); request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed! request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(request); Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename, Snackbar.LENGTH_SHORT).show(); } }); snackbar.show(); } }); helper_browser.toolbar(Browser_left.this, Browser_right.class, mWebView, toolbar); helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar); helper_editText.editText_FocusChange(editText, Browser_left.this); helper_main.grantPermissionsStorage(Browser_left.this); onNewIntent(getIntent()); }
From source file:com.danvelazco.fbwrapper.activity.BaseFacebookWebViewActivity.java
/** * Update the cache mode depending on the network connection state of the device. *///from w ww .j av a2 s .c o m private void updateCacheMode() { if (checkNetworkConnection()) { Logger.d(LOG_TAG, "Setting cache mode to: LOAD_DEFAULT"); mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT); } else { Logger.d(LOG_TAG, "Setting cache mode to: LOAD_CACHE_ONLY"); mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY); } }
From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface", "NewApi" }) @Override/*from w ww . j a va2 s . c o m*/ public void onCreate(Bundle savedInstanceState) { if (CloudConstants.isContentBrandingApp()) { super.setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen); } super.onCreate(savedInstanceState); setContentView(R.layout.action_screen); mBranding = (WebView) findViewById(R.id.branding); WebSettings brandingSettings = mBranding.getSettings(); brandingSettings.setJavaScriptEnabled(true); brandingSettings.setCacheMode(WebSettings.LOAD_DEFAULT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { brandingSettings.setAllowFileAccessFromFileURLs(true); } mBrandingHttp = (WebView) findViewById(R.id.branding_http); mBrandingHttp.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); WebSettings brandingSettingsHttp = mBrandingHttp.getSettings(); brandingSettingsHttp.setJavaScriptEnabled(true); brandingSettingsHttp.setCacheMode(WebSettings.LOAD_DEFAULT); if (CloudConstants.isContentBrandingApp()) { mSoundThread = new HandlerThread("rogerthat_actionscreenactivity_sound"); mSoundThread.start(); Looper looper = mSoundThread.getLooper(); mSoundHandler = new Handler(looper); int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); if (cameraPermission == PackageManager.PERMISSION_GRANTED) { mQRCodeScanner = QRCodeScanner.getInstance(this); final LinearLayout previewHolder = (LinearLayout) findViewById(R.id.preview_view); previewHolder.addView(mQRCodeScanner.view); } mBranding.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { initFullScreenForContentBranding(); } }); mBrandingHttp.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { initFullScreenForContentBranding(); } }); } final View brandingHeader = findViewById(R.id.branding_header_container); final ImageView brandingHeaderClose = (ImageView) findViewById(R.id.branding_header_close); final TextView brandingHeaderText = (TextView) findViewById(R.id.branding_header_text); brandingHeaderClose .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text))); brandingHeaderClose.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.onResume(); } brandingHeader.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl("about:blank"); } }); final View brandingFooter = findViewById(R.id.branding_footer_container); if (CloudConstants.isContentBrandingApp()) { brandingHeaderClose.setVisibility(View.GONE); final ImageView brandingFooterClose = (ImageView) findViewById(R.id.branding_footer_close); final TextView brandingFooterText = (TextView) findViewById(R.id.branding_footer_text); brandingFooterText.setText(getString(R.string.back)); brandingFooterClose .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text))); brandingFooter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.onResume(); } brandingHeader.setVisibility(View.GONE); brandingFooter.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl("about:blank"); } }); } final RelativeLayout openPreview = (RelativeLayout) findViewById(R.id.preview_holder); openPreview.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.previewHolderClicked(); } } }); mBranding.addJavascriptInterface(new JSInterface(this), "__rogerthat__"); mBranding.setWebChromeClient(new WebChromeClient() { @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { if (sourceID != null) { try { sourceID = new File(sourceID).getName(); } catch (Exception e) { L.d("Could not get fileName of sourceID: " + sourceID, e); } } if (mIsHtmlContent) { L.i("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message); } else { L.d("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message); } } }); mBranding.setWebViewClient(new WebViewClient() { private boolean isExternalUrl(String url) { for (String regularExpression : mBrandingResult.externalUrlPatterns) { if (url.matches(regularExpression)) { return true; } } return false; } @SuppressLint("DefaultLocale") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { L.i("Branding is loading url: " + url); Uri uri = Uri.parse(url); String lowerCaseUrl = url.toLowerCase(); if (lowerCaseUrl.startsWith("tel:") || lowerCaseUrl.startsWith("mailto:") || isExternalUrl(url)) { Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; } else if (lowerCaseUrl.startsWith(POKE)) { String tag = url.substring(POKE.length()); poke(tag); return true; } else if (lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://")) { if (mQRCodeScanner != null) { mQRCodeScanner.onPause(); } brandingHeaderText.setText(getString(R.string.loading)); brandingHeader.setVisibility(View.VISIBLE); if (CloudConstants.isContentBrandingApp()) { brandingFooter.setVisibility(View.VISIBLE); } mBranding.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl(url); return true; } else { brandingHeader.setVisibility(View.GONE); brandingFooter.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); } return false; } @Override public void onPageFinished(WebView view, String url) { L.i("onPageFinished " + url); if (!mInfoSet && mService != null && mIsHtmlContent) { Map<String, Object> info = mFriendsPlugin.getRogerthatUserAndServiceInfo(mServiceEmail, mServiceFriend); executeJS(true, "if (typeof rogerthat !== 'undefined') rogerthat._setInfo(%s)", JSONValue.toJSONString(info)); mInfoSet = true; } } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { L.i("Checking access to: '" + url + "'"); final URL parsedUrl; try { parsedUrl = new URL(url); } catch (MalformedURLException e) { L.d("Webview tried to load malformed URL"); return new WebResourceResponse("text/plain", "UTF-8", null); } if (!parsedUrl.getProtocol().equals("file")) { return null; } File urlPath = new File(parsedUrl.getPath()); if (urlPath.getAbsolutePath().startsWith(mBrandingResult.dir.getAbsolutePath())) { return null; } L.d("404: Webview tries to load outside its sandbox."); return new WebResourceResponse("text/plain", "UTF-8", null); } }); mBrandingHttp.setWebViewClient(new WebViewClient() { @SuppressLint("DefaultLocale") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { L.i("BrandingHttp is loading url: " + url); return false; } @Override public void onPageFinished(WebView view, String url) { brandingHeaderText.setText(view.getTitle()); L.i("onPageFinished " + url); } }); Intent intent = getIntent(); mBrandingKey = intent.getStringExtra(BRANDING_KEY); mServiceEmail = intent.getStringExtra(SERVICE_EMAIL); mItemTagHash = intent.getStringExtra(ITEM_TAG_HASH); mItemLabel = intent.getStringExtra(ITEM_LABEL); mItemCoords = intent.getLongArrayExtra(ITEM_COORDS); mRunInBackground = intent.getBooleanExtra(RUN_IN_BACKGROUND, true); }
From source file:org.chromium.android_webview.test.AwSettingsTest.java
@SmallTest @Feature({ "AndroidWebView", "Preferences" }) public void testCacheMode() throws Throwable { final TestAwContentsClient contentClient = new TestAwContentsClient(); final AwTestContainerView testContainer = createAwTestContainerViewOnMainSync(contentClient); final AwContents awContents = testContainer.getAwContents(); final AwSettings awSettings = getAwSettingsOnUiThread(testContainer.getAwContents()); clearCacheOnUiThread(awContents, true); assertEquals(WebSettings.LOAD_DEFAULT, awSettings.getCacheMode()); TestWebServer webServer = null;/*from ww w .j a va 2 s . co m*/ try { webServer = new TestWebServer(false); final String htmlPath = "/testCacheMode.html"; final String url = webServer.setResponse(htmlPath, "response", null); awSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url); assertEquals(1, webServer.getRequestCount(htmlPath)); loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url); assertEquals(1, webServer.getRequestCount(htmlPath)); awSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url); assertEquals(2, webServer.getRequestCount(htmlPath)); loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url); assertEquals(3, webServer.getRequestCount(htmlPath)); awSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY); loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url); assertEquals(3, webServer.getRequestCount(htmlPath)); loadUrlSync(awContents, contentClient.getOnPageFinishedHelper(), url); assertEquals(3, webServer.getRequestCount(htmlPath)); final String htmlNotInCachePath = "/testCacheMode-not-in-cache.html"; final String urlNotInCache = webServer.setResponse(htmlNotInCachePath, "", null); loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(), contentClient.getOnReceivedErrorHelper(), urlNotInCache); assertEquals(0, webServer.getRequestCount(htmlNotInCachePath)); } finally { if (webServer != null) webServer.shutdown(); } }
From source file:org.chromium.android_webview.test.AwSettingsTest.java
@SmallTest @Feature({ "AndroidWebView", "Preferences" }) // As our implementation of network loads blocking uses the same net::URLRequest settings, make // sure that setting cache mode doesn't accidentally enable network loads. The reference // behaviour is that when network loads are blocked, setting cache mode has no effect. public void testCacheModeWithBlockedNetworkLoads() throws Throwable { final TestAwContentsClient contentClient = new TestAwContentsClient(); final AwTestContainerView testContainer = createAwTestContainerViewOnMainSync(contentClient); final AwContents awContents = testContainer.getAwContents(); final AwSettings awSettings = getAwSettingsOnUiThread(testContainer.getAwContents()); clearCacheOnUiThread(awContents, true); assertEquals(WebSettings.LOAD_DEFAULT, awSettings.getCacheMode()); awSettings.setBlockNetworkLoads(true); TestWebServer webServer = null;/*from w w w . jav a 2 s.c o m*/ try { webServer = new TestWebServer(false); final String htmlPath = "/testCacheModeWithBlockedNetworkLoads.html"; final String url = webServer.setResponse(htmlPath, "response", null); loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(), contentClient.getOnReceivedErrorHelper(), url); assertEquals(0, webServer.getRequestCount(htmlPath)); awSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(), contentClient.getOnReceivedErrorHelper(), url); assertEquals(0, webServer.getRequestCount(htmlPath)); awSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(), contentClient.getOnReceivedErrorHelper(), url); assertEquals(0, webServer.getRequestCount(htmlPath)); awSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY); loadUrlSyncAndExpectError(awContents, contentClient.getOnPageFinishedHelper(), contentClient.getOnReceivedErrorHelper(), url); assertEquals(0, webServer.getRequestCount(htmlPath)); } finally { if (webServer != null) webServer.shutdown(); } }