List of usage examples for android.webkit WebSettings setAllowFileAccess
public abstract void setAllowFileAccess(boolean allow);
From source file:org.golang.app.WViewActivity.java
private void initWebView(WebView webView) { WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setAllowFileAccess(true); settings.setDomStorageEnabled(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); settings.setLoadWithOverviewMode(true); settings.setUseWideViewPort(true);//from www. j av a2s. co m settings.setSupportZoom(true); // settings.setPluginsEnabled(true); methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true }); // settings.setPluginState(PluginState.ON); methodInvoke(settings, "setPluginState", new Class[] { PluginState.class }, new Object[] { PluginState.ON }); // settings.setPluginsEnabled(true); methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true }); // settings.setAllowUniversalAccessFromFileURLs(true); methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true }); // settings.setAllowFileAccessFromFileURLs(true); methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true }); webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webView.clearHistory(); webView.clearFormData(); webView.clearCache(true); webView.setWebChromeClient(new MyWebChromeClient()); // webView.setDownloadListener(downloadListener); }
From source file:ch.gianulli.flashcards.ui.Flashcard.java
/** * @param view Instance of flashcard.xml *//*from w w w .j a v a 2 s .co m*/ public Flashcard(View view, OnCardAnsweredListener listener) { mListener = listener; mView = view; mQuestion = (StyledMarkdownView) view.findViewById(R.id.question); mAnswer = (StyledMarkdownView) view.findViewById(R.id.answer); mCardView = (CardView) view.findViewById(R.id.card); mButtonBar = view.findViewById(R.id.button_bar); mCorrectButton = (Button) view.findViewById(R.id.correct_button); mWrongButton = (Button) view.findViewById(R.id.wrong_button); mContext = mView.getContext(); // Load colors int[] attrs = { android.R.attr.textColorSecondary, android.R.attr.textColorPrimary }; TypedArray ta = mView.getContext().obtainStyledAttributes(R.style.AppTheme, attrs); sDeactivatedTextColor = colorToCSSString(ta.getColor(0, 0)); sDefaultTextColor = colorToCSSString(ta.getColor(1, 0)); ta.recycle(); sGreenTextColor = colorToCSSString(ContextCompat.getColor(mContext, R.color.green)); mQuestionColor = sDefaultTextColor; mAnswerColor = sGreenTextColor; // Make question visible mQuestion.setAlpha(1.0f); mAnswer.setAlpha(0.0f); // Setup WebViews WebSettings settings = mQuestion.getSettings(); settings.setDefaultFontSize(mFontSize); settings.setLoadsImagesAutomatically(true); settings.setGeolocationEnabled(false); settings.setAllowFileAccess(false); settings.setDisplayZoomControls(false); settings.setNeedInitialFocus(false); settings.setSupportZoom(false); settings.setSaveFormData(false); settings.setJavaScriptEnabled(true); mQuestion.setHorizontalScrollBarEnabled(false); mQuestion.setVerticalScrollBarEnabled(false); settings = mAnswer.getSettings(); settings.setDefaultFontSize(mFontSize); settings.setLoadsImagesAutomatically(true); settings.setGeolocationEnabled(false); settings.setAllowFileAccess(false); settings.setDisplayZoomControls(false); settings.setNeedInitialFocus(false); settings.setSupportZoom(false); settings.setSaveFormData(false); settings.setJavaScriptEnabled(true); mAnswer.setHorizontalScrollBarEnabled(false); mAnswer.setVerticalScrollBarEnabled(false); // Hack to disable text selection in WebViews mQuestion.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { return true; } }); mAnswer.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { return true; } }); // Card should "turn" on click final FrameLayout questionLayout = (FrameLayout) view.findViewById(R.id.question_layout); questionLayout.setClickable(true); questionLayout.setOnTouchListener(mTurnCardListener); mQuestion.setOnTouchListener(mTurnCardListener); mAnswer.setOnTouchListener(mTurnCardListener); // Deactivate card when user answers it mCorrectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deactivateCard(true); mListener.onCardAnswered(mCard, true); } }); mWrongButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deactivateCard(false); mListener.onCardAnswered(mCard, false); } }); // Limit card width to 400dp ViewTreeObserver observer = mCardView.getViewTreeObserver(); final int width480dp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, view.getContext().getResources().getDisplayMetrics()); observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (mCardView.getWidth() > width480dp) { ViewGroup.LayoutParams layoutParams = mCardView.getLayoutParams(); layoutParams.width = width480dp; mCardView.setLayoutParams(layoutParams); mCardView.requestLayout(); return false; } return true; } }); }
From source file:com.example.administrator.mywebviewdrawsign.SysWebView.java
/** * Initialize webview.//from w w w. j av a2 s . com */ @SuppressLint({ "NewApi", "SetJavaScriptEnabled" }) private void setup() { this.setInitialScale(0); this.setVerticalScrollBarEnabled(true); this.setHorizontalScrollBarEnabled(true); this.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.getSettings(); settings.setBuiltInZoomControls(false);// ?? settings.setUseWideViewPort(false); settings.setLoadWithOverviewMode(true); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); settings.setAllowFileAccess(true); settings.setAppCacheMaxSize(1024 * 1024 * 32); settings.setAppCachePath(mContext.getFilesDir().getPath() + "/cache"); settings.setAppCacheEnabled(true); settings.setCacheMode(WebSettings.LOAD_DEFAULT); // Set Cache Mode: LOAD_NO_CACHE is noly for debug //settings.setCacheMode(WebSettings.LOAD_NO_CACHE); //enablePageCache(settings,5); //enableWorkers(settings); // Enable database settings.setDatabaseEnabled(true); String databasePath = mContext.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); // Improve render performance settings.setRenderPriority(WebSettings.RenderPriority.HIGH); if (Build.VERSION.SDK_INT >= 21) { settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } }
From source file:com.owncloud.android.ui.dialog.LoginWebViewDialog.java
@SuppressWarnings("deprecation") @SuppressLint("SetJavaScriptEnabled") @Override/*w ww . j a va 2 s . c o m*/ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log_OC.v(TAG, "onCreateView, savedInsanceState is " + savedInstanceState); // Inflate layout of the dialog RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.webview_dialog, container, false); // null parent view because it will go in the dialog layout if (mWebView == null) { // initialize the WebView mWebView = new SsoWebView(getActivity().getApplicationContext()); mWebView.setFocusable(true); mWebView.setFocusableInTouchMode(true); mWebView.setClickable(true); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setSavePassword(false); webSettings.setUserAgentString(MainApp.getUserAgent()); webSettings.setSaveFormData(false); // next two settings grant that non-responsive webs are zoomed out when loaded webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); // next three settings allow the user use pinch gesture to zoom in / out webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); webSettings.setDisplayZoomControls(false); webSettings.setAllowFileAccess(false); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.removeAllCookie(); mWebView.loadUrl(mInitialUrl); } mWebViewClient.addTargetUrls(mTargetUrls); mWebView.setWebViewClient(mWebViewClient); // add the webview into the layout RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); ssoRootView.addView(mWebView, layoutParams); ssoRootView.requestLayout(); return ssoRootView; }
From source file:com.air.mobilebrowser.BrowserActivity.java
/** * Configure a webview to use the activity as * its client, and update its settings with * the desired parameters for the activity. * @param webView the webview to configure. *///from ww w.j a va 2s . c om private void configureWebView(WebView webView) { webView.clearCache(true); webView.setWebViewClient(new SecureWebClient(this)); WebSettings settings = mWebView.getSettings(); settings.setBuiltInZoomControls(true); settings.setJavaScriptEnabled(true); // settings.setPluginState(PluginState.ON_DEMAND); settings.setPluginState(PluginState.ON); settings.setAllowFileAccess(true); settings.setAllowContentAccess(true); settings.setSaveFormData(false); settings.setSavePassword(false); webView.clearFormData(); settings.setDomStorageEnabled(true); String defaultUserAgent = settings.getUserAgentString(); StringBuilder sb = new StringBuilder(); sb.append(defaultUserAgent); sb.append(" SmarterSecureBrowser/1.0"); sb.append(" OS/"); sb.append(mDeviceStatus.operatingSystem); sb.append(" Version/"); sb.append(mDeviceStatus.operatingSystemVersion); sb.append(" Model/"); sb.append(mDeviceStatus.model); settings.setUserAgentString(sb.toString()); }
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);/* w w w. ja v a 2 s. c o m*/ 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:mgks.os.webview.MainActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" }) @Override//from w ww .j a v a2 s .co m protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.w("READ_PERM = ", Manifest.permission.READ_EXTERNAL_STORAGE); Log.w("WRITE_PERM = ", Manifest.permission.WRITE_EXTERNAL_STORAGE); //Prevent the app from being started again when it is still alive in the background if (!isTaskRoot()) { finish(); return; } setContentView(R.layout.activity_main); asw_view = findViewById(R.id.msw_view); final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh); if (ASWP_PULLFRESH) { pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { pull_fresh(); pullfresh.setRefreshing(false); } }); asw_view.getViewTreeObserver() .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (asw_view.getScrollY() == 0) { pullfresh.setEnabled(true); } else { pullfresh.setEnabled(false); } } }); } else { pullfresh.setRefreshing(false); pullfresh.setEnabled(false); } if (ASWP_PBAR) { asw_progress = findViewById(R.id.msw_progress); } else { findViewById(R.id.msw_progress).setVisibility(View.GONE); } asw_loading_text = findViewById(R.id.msw_loading_text); Handler handler = new Handler(); //Launching app rating request if (ASWP_RATINGS) { handler.postDelayed(new Runnable() { public void run() { get_rating(); } }, 1000 * 60); //running request after few moments } //Getting basic device information get_info(); //Getting GPS location of device if given permission if (ASWP_LOCATION && !check_permission(1)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } get_location(); //Webview settings; defaults are customized for best performance WebSettings webSettings = asw_view.getSettings(); if (!ASWP_OFFLINE) { webSettings.setJavaScriptEnabled(ASWP_JSCRIPT); } webSettings.setSaveFormData(ASWP_SFORM); webSettings.setSupportZoom(ASWP_ZOOM); webSettings.setGeolocationEnabled(ASWP_LOCATION); webSettings.setAllowFileAccess(true); webSettings.setAllowFileAccessFromFileURLs(true); webSettings.setAllowUniversalAccessFromFileURLs(true); webSettings.setUseWideViewPort(true); webSettings.setDomStorageEnabled(true); asw_view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return true; } }); asw_view.setHapticFeedbackEnabled(false); asw_view.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) { if (!check_permission(2)) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE }, file_perm); } else { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setMimeType(mimeType); String cookies = CookieManager.getInstance().getCookie(url); request.addRequestHeader("cookie", cookies); request.addRequestHeader("User-Agent", userAgent); request.setDescription(getString(R.string.dl_downloading)); request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType)); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); assert dm != null; dm.enqueue(request); Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG) .show(); } } }); if (Build.VERSION.SDK_INT >= 21) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark)); asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } else if (Build.VERSION.SDK_INT >= 19) { asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null); } asw_view.setVerticalScrollBarEnabled(false); asw_view.setWebViewClient(new Callback()); //Rendering the default URL aswm_view(ASWV_URL, false); asw_view.setWebChromeClient(new WebChromeClient() { //Handling input[type="file"] requests for android API 16+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { if (ASWP_FUPLOAD) { asw_file_message = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req); } } //Handling input[type="file"] requests for android API 21+ public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (check_permission(2) && check_permission(3)) { if (ASWP_FUPLOAD) { if (asw_file_path != null) { asw_file_path.onReceiveValue(null); } asw_file_path = filePathCallback; Intent takePictureIntent = null; if (ASWP_CAMUPLOAD) { takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) { File photoFile = null; try { photoFile = create_image(); takePictureIntent.putExtra("PhotoPath", asw_cam_message); } catch (IOException ex) { Log.e(TAG, "Image file creation failed", ex); } if (photoFile != null) { asw_cam_message = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); } else { takePictureIntent = null; } } } Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); if (!ASWP_ONLYCAM) { contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType(ASWV_F_TYPE); if (ASWP_MULFILE) { contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } } 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, getString(R.string.fl_chooser)); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, asw_file_req); } return true; } else { get_file(); return false; } } //Getting webview rendering progress @Override public void onProgressChanged(WebView view, int p) { if (ASWP_PBAR) { asw_progress.setProgress(p); if (p == 100) { asw_progress.setProgress(0); } } } // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { if (Build.VERSION.SDK_INT < 23 || check_permission(1)) { // location permissions were granted previously so auto-approve callback.invoke(origin, true, false); } else { // location permissions not granted so request them ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm); } } }); if (getIntent().getData() != null) { String path = getIntent().getDataString(); /* If you want to check or use specific directories or schemes or hosts Uri data = getIntent().getData(); String scheme = data.getScheme(); String host = data.getHost(); List<String> pr = data.getPathSegments(); String param1 = pr.get(0); */ aswm_view(path, false); } }
From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java
private void setWebView(final GalleryItemViewTag tag, final File file) { runOnUiThread(new Runnable() { private boolean oomFlag = false; private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); private void prepareWebView(WebView webView) { webView.setBackgroundColor(Color.TRANSPARENT); webView.setInitialScale(100); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { CompatibilityImpl.setScrollbarFadingEnabled(webView, true); }/* w w w. j a v a 2s.c o m*/ WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setSupportZoom(true); settings.setAllowFileAccess(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { CompatibilityImpl.setDefaultZoomFAR(settings); CompatibilityImpl.setLoadWithOverviewMode(settings, true); } settings.setUseWideViewPort(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { CompatibilityImpl.setBlockNetworkLoads(settings, true); } setScaleWebView(webView); } private void setScaleWebView(final WebView webView) { Runnable callSetScaleWebView = new Runnable() { @Override public void run() { setPrivateScaleWebView(webView); } }; Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); if (resolution.equals(0, 0)) { // wait until the view is measured and its size is known AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView); } else { callSetScaleWebView.run(); } } private void setPrivateScaleWebView(WebView webView) { Point imageSize = getImageSize(file); Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y); double scaleX = (double) resolution.x / (double) imageSize.x; double scaleY = (double) resolution.y / (double) imageSize.y; int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d); scale = Math.max(scale, 1); //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX; if (picdpi >= 240) { CompatibilityImpl.setDefaultZoomFAR(webView.getSettings()); } else if (picdpi <= 120) { CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings()); } else { CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings()); } } webView.setInitialScale(scale); webView.setPadding(0, 0, 0, 0); } private Point getImageSize(File file) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); return new Point(options.outWidth, options.outHeight); } private boolean useFallback(File file) { String path = file.getPath().toLowerCase(Locale.US); if (path.endsWith(".png")) return false; if (path.endsWith(".jpg")) return false; if (path.endsWith(".gif")) return false; if (path.endsWith(".jpeg")) return false; if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) return false; return true; } @Override public void run() { try { recycleTag(tag, false); WebView webView = new WebViewFixed(GalleryActivity.this); webView.setLayoutParams(MATCH_PARAMS); tag.layout.addView(webView); if (settings.fallbackWebView() || useFallback(file)) { prepareWebView(webView); webView.loadUrl(Uri.fromFile(file).toString()); } else { JSWebView.setImage(webView, file); } tag.thumbnailView.setVisibility(View.GONE); tag.loadingView.setVisibility(View.GONE); tag.layout.setVisibility(View.VISIBLE); } catch (OutOfMemoryError oom) { System.gc(); Logger.e(TAG, oom); if (!oomFlag) { oomFlag = true; run(); } else showError(tag, getString(R.string.error_out_of_memory)); } } }); }
From source file:nya.miku.wishmaster.ui.GalleryActivity.java
private void setWebView(final GalleryItemViewTag tag, final File file) { runOnUiThread(new Runnable() { private boolean oomFlag = false; private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); private void prepareWebView(WebView webView) { webView.setBackgroundColor(Color.TRANSPARENT); webView.setInitialScale(100); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) { CompatibilityImpl.setScrollbarFadingEnabled(webView, true); }//w ww . ja v a2 s .co m WebSettings settings = webView.getSettings(); settings.setBuiltInZoomControls(true); settings.setSupportZoom(true); settings.setAllowFileAccess(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { CompatibilityImpl.setDefaultZoomFAR(settings); CompatibilityImpl.setLoadWithOverviewMode(settings, true); } settings.setUseWideViewPort(true); settings.setCacheMode(WebSettings.LOAD_NO_CACHE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { CompatibilityImpl.setBlockNetworkLoads(settings, true); } setScaleWebView(webView); } private void setScaleWebView(final WebView webView) { Runnable callSetScaleWebView = new Runnable() { @Override public void run() { setPrivateScaleWebView(webView); } }; Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); if (resolution.equals(0, 0)) { // wait until the view is measured and its size is known AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView); } else { callSetScaleWebView.run(); } } private void setPrivateScaleWebView(WebView webView) { Point imageSize = getImageSize(file); Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight()); //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y); double scaleX = (double) resolution.x / (double) imageSize.x; double scaleY = (double) resolution.y / (double) imageSize.y; int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d); scale = Math.max(scale, 1); //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) { double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX; if (picdpi >= 240) { CompatibilityImpl.setDefaultZoomFAR(webView.getSettings()); } else if (picdpi <= 120) { CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings()); } else { CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings()); } } webView.setInitialScale(scale); webView.setPadding(0, 0, 0, 0); } private Point getImageSize(File file) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); return new Point(options.outWidth, options.outHeight); } private boolean useFallback(File file) { String path = file.getPath().toLowerCase(Locale.US); if (path.endsWith(".png")) return false; if (path.endsWith(".jpg")) return false; if (path.endsWith(".gif")) return false; if (path.endsWith(".jpeg")) return false; if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) return false; return true; } @Override public void run() { try { recycleTag(tag, false); WebView webView = new WebViewFixed(GalleryActivity.this); webView.setLayoutParams(MATCH_PARAMS); tag.layout.addView(webView); if (settings.fallbackWebView() || useFallback(file)) { prepareWebView(webView); webView.loadUrl(Uri.fromFile(file).toString()); } else { JSWebView.setImage(webView, file); } tag.thumbnailView.setVisibility(View.GONE); tag.loadingView.setVisibility(View.GONE); tag.layout.setVisibility(View.VISIBLE); } catch (OutOfMemoryError oom) { MainApplication.freeMemory(); Logger.e(TAG, oom); if (!oomFlag) { oomFlag = true; run(); } else showError(tag, getString(R.string.error_out_of_memory)); } } }); }
From source file:com.creativtrendz.folio.ui.FolioWebViewScroll.java
@SuppressLint({ "SetJavaScriptEnabled" }) protected void init(Context context) { if (context instanceof Activity) { mActivity = new WeakReference<>((Activity) context); }// ww w. java 2s .c om mLanguageIso3 = getLanguageIso3(); setFocusable(true); setFocusableInTouchMode(true); setSaveEnabled(true); final String filesDir = context.getFilesDir().getPath(); final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER; final WebSettings webSettings = getSettings(); webSettings.setAllowFileAccess(false); setAllowAccessFromFileUrls(webSettings, false); webSettings.setBuiltInZoomControls(false); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); if (Build.VERSION.SDK_INT < 18) { webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); } webSettings.setDatabaseEnabled(true); if (Build.VERSION.SDK_INT < 19) { webSettings.setDatabasePath(databaseDir); } setMixedContentAllowed(webSettings, true); setThirdPartyCookiesEnabled(true); super.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { if (!hasError()) { if (mListener != null) { mListener.onPageStarted(url, favicon); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageStarted(view, url, favicon); } } @Override public void onPageFinished(WebView view, String url) { if (!hasError()) { if (mListener != null) { mListener.onPageFinished(url); } } if (mCustomWebViewClient != null) { mCustomWebViewClient.onPageFinished(view, url); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { setLastError(); if (mListener != null) { mListener.onPageError(errorCode, description, failingUrl); } if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (isHostnameAllowed(url)) { return mCustomWebViewClient != null && mCustomWebViewClient.shouldOverrideUrlLoading(view, url); } else { if (mListener != null) { mListener.onExternalPageRequest(url); } return true; } } @Override public void onLoadResource(WebView view, String url) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onLoadResource(view, url); } else { super.onLoadResource(view, url); } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (Build.VERSION.SDK_INT >= 11) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, url); } else { return super.shouldInterceptRequest(view, url); } } else { return null; } } @SuppressLint("NewApi") @SuppressWarnings("all") public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldInterceptRequest(view, request); } else { return super.shouldInterceptRequest(view, request); } } else { return null; } } @Override public void onFormResubmission(WebView view, Message dontResend, Message resend) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onFormResubmission(view, dontResend, resend); } else { super.onFormResubmission(view, dontResend, resend); } } @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { if (mCustomWebViewClient != null) { mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload); } else { super.doUpdateVisitedHistory(view, url, isReload); } } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedSslError(view, handler, error); } else { super.onReceivedSslError(view, handler, error); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedClientCertRequest(view, request); } else { super.onReceivedClientCertRequest(view, request); } } } @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm); } else { super.onReceivedHttpAuthRequest(view, handler, host, realm); } } @Override public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { return mCustomWebViewClient.shouldOverrideKeyEvent(view, event); } else { return super.shouldOverrideKeyEvent(view, event); } } @Override public void onUnhandledKeyEvent(WebView view, KeyEvent event) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onUnhandledKeyEvent(view, event); } else { super.onUnhandledKeyEvent(view, event); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onUnhandledInputEvent(WebView view, InputEvent event) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onUnhandledInputEvent(view, event); } else { super.onUnhandledInputEvent(view, event); } } } @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onScaleChanged(view, oldScale, newScale); } else { super.onScaleChanged(view, oldScale, newScale); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onReceivedLoginRequest(WebView view, String realm, String account, String args) { if (Build.VERSION.SDK_INT >= 12) { if (mCustomWebViewClient != null) { mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args); } else { super.onReceivedLoginRequest(view, realm, account, args); } } } }); super.setWebChromeClient(new WebChromeClient() { // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg) { openFileChooser(uploadMsg, null); } // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method) public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { openFileChooser(uploadMsg, acceptType, null); } // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method) @SuppressWarnings("unused") public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { openFileInput(uploadMsg, null); } // file upload callback (Android 5.0 (API level 21) -- current) (public method) @SuppressWarnings("all") public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { openFileInput(null, filePathCallback); return true; } @Override public void onProgressChanged(WebView view, int newProgress) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onProgressChanged(view, newProgress); } else { super.onProgressChanged(view, newProgress); } } @Override public void onReceivedTitle(WebView view, String title) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTitle(view, title); } else { super.onReceivedTitle(view, title); } } @Override public void onReceivedIcon(WebView view, Bitmap icon) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedIcon(view, icon); } else { super.onReceivedIcon(view, icon); } } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed); } else { super.onReceivedTouchIconUrl(view, url, precomposed); } } @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, callback); } else { super.onShowCustomView(view, callback); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { if (Build.VERSION.SDK_INT >= 14) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback); } else { super.onShowCustomView(view, requestedOrientation, callback); } } } @Override public void onHideCustomView() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onHideCustomView(); } else { super.onHideCustomView(); } } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } else { return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } } @Override public void onRequestFocus(WebView view) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onRequestFocus(view); } else { super.onRequestFocus(view); } } @Override public void onCloseWindow(WebView window) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onCloseWindow(window); } else { super.onCloseWindow(window); } } @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsAlert(view, url, message, result); } else { return super.onJsAlert(view, url, message, result); } } @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsConfirm(view, url, message, result); } else { return super.onJsConfirm(view, url, message, result); } } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result); } else { return super.onJsPrompt(view, url, message, defaultValue, result); } } @Override public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result); } else { return super.onJsBeforeUnload(view, url, message, result); } } @Override public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { if (mGeolocationEnabled) { callback.invoke(origin, true, false); } else { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback); } else { super.onGeolocationPermissionsShowPrompt(origin, callback); } } } @Override public void onGeolocationPermissionsHidePrompt() { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onGeolocationPermissionsHidePrompt(); } else { super.onGeolocationPermissionsHidePrompt(); } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequest(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequest(request); } else { super.onPermissionRequest(request); } } } @SuppressLint("NewApi") @SuppressWarnings("all") public void onPermissionRequestCanceled(PermissionRequest request) { if (Build.VERSION.SDK_INT >= 21) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onPermissionRequestCanceled(request); } else { super.onPermissionRequestCanceled(request); } } } @Override public boolean onJsTimeout() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onJsTimeout(); } else { return super.onJsTimeout(); } } @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID); } else { super.onConsoleMessage(message, lineNumber, sourceID); } } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.onConsoleMessage(consoleMessage); } else { return super.onConsoleMessage(consoleMessage); } } @Override public Bitmap getDefaultVideoPoster() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getDefaultVideoPoster(); } else { return super.getDefaultVideoPoster(); } } @Override public View getVideoLoadingProgressView() { if (mCustomWebChromeClient != null) { return mCustomWebChromeClient.getVideoLoadingProgressView(); } else { return super.getVideoLoadingProgressView(); } } @Override public void getVisitedHistory(ValueCallback<String[]> callback) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.getVisitedHistory(callback); } else { super.getVisitedHistory(callback); } } @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } else { super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota, quotaUpdater); } } @Override public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) { if (mCustomWebChromeClient != null) { mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } else { super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater); } } }); setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { if (mListener != null) { mListener.onDownloadRequested(url, userAgent, contentDisposition, mimetype, contentLength); } } }); }