Example usage for android.webkit WebSettings setAllowUniversalAccessFromFileURLs

List of usage examples for android.webkit WebSettings setAllowUniversalAccessFromFileURLs

Introduction

In this page you can find the example usage for android.webkit WebSettings setAllowUniversalAccessFromFileURLs.

Prototype

public abstract void setAllowUniversalAccessFromFileURLs(boolean flag);

Source Link

Document

Sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin.

Usage

From source file:com.sonnychen.aviationhk.views.BookingFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override/* ww  w  . jav a 2s  .c om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Bundle bundle = getArguments();
    if (bundle != null && !TextUtils.isEmpty(bundle.getString(BOOKING_TYPE_PARAM))) {
        Log.v("BOOKING-UI", "Argument: " + bundle.getString(BOOKING_TYPE_PARAM));
        bookingType = BookingType.valueOf(bundle.getString(BOOKING_TYPE_PARAM));
    }

    Log.v("BOOKING-UI", "Starting");
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_booking, container, false);
    mProgressBar = ((ProgressBar) view.findViewById(R.id.progress));
    mWebView = ((WebView) view.findViewById(R.id.booking_html));

    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setAllowFileAccessFromFileURLs(true);
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setBuiltInZoomControls(true);
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.addJavascriptInterface(new JSInterface(getActivity(), mWebView), "Android");
    mWebView.setInitialScale(1);

    // download PDF async
    new DownloadFileTask() {
        @Override
        protected void onPostExecute(Byte[] data) {
            // save data to file
            try {
                FileOutputStream fileOutputStream = getActivity().openFileOutput(
                        bookingType == BookingType.HELICOPTER ? "helicopter.pdf" : "fixedwing.pdf",
                        Context.MODE_PRIVATE);
                fileOutputStream.write(getbytes(data));
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            displayPDF();
            // unfortunately HAKC does not have a valid SSL certificate
        }
    }.execute(bookingType == BookingType.HELICOPTER ? "http://aviationclub.hk/doc/helicopter_booking2.pdf"
            : "http://aviationclub.hk/doc/fixwing_booking2.pdf");
    return view;
}

From source file:com.creativtrendz.folio.ui.FolioWebViewScroll.java

@SuppressLint("NewApi")
protected static void setAllowAccessFromFileUrls(final WebSettings webSettings, final boolean allowed) {
    if (Build.VERSION.SDK_INT >= 16) {
        webSettings.setAllowFileAccessFromFileURLs(allowed);
        webSettings.setAllowUniversalAccessFromFileURLs(allowed);
    }/*w  w w .j  av a 2 s  .c  om*/
}

From source file:com.paulshantanu.bputapp.PdfViewerAcitvity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pdf_notice);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setSubtitle("View Notice");

    String link = getIntent().getExtras().getString("link");
    Log.i("debug", "pdfintent: " + link);

    url = URLDecoder.getDecodedUrl(link);

    progressBar = ButteryProgressBar.getInstance(PdfViewerAcitvity.this);
    progressBar.setVisibility(View.VISIBLE);

    webView = (WebView) findViewById(R.id.notice_view);
    webView.setVisibility(View.INVISIBLE);
    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { //required for running javascript on android 4.1 or later
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
    }/*from   w  w  w  . j a  v  a 2 s.  co  m*/
    settings.setBuiltInZoomControls(true);
    webView.setWebChromeClient(new WebChromeClient());

    new DownloadTask(PdfViewerAcitvity.this).execute(url);
}

From source file:com.mobicage.rogerthat.plugins.messaging.AttachmentViewerActivity.java

@SuppressLint({ "SetJavaScriptEnabled" })
protected void updateView(boolean isUpdate) {
    T.UI();//from  w  w w.  j  av a 2  s .  c  o  m

    if (!isUpdate && mGenerateThumbnail) {
        File thumbnail = new File(mFile.getAbsolutePath() + ".thumb");
        if (!thumbnail.exists()) {
            boolean isImage = mContentType.toLowerCase(Locale.US).startsWith("image/");
            boolean isVideo = !isImage && mContentType.toLowerCase(Locale.US).startsWith("video/");
            try {
                // Try to generate a thumbnail
                mMessagingPlugin.createAttachmentThumbnail(mFile.getAbsolutePath(), isImage, isVideo);
            } catch (Exception e) {
                L.e("Failed to generate attachment thumbnail", e);
            }
        }
    }

    final String fileOnDisk = "file://" + mFile.getAbsolutePath();

    if (mContentType.toLowerCase(Locale.US).startsWith("video/")) {
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoview);

        Uri video = Uri.parse(fileOnDisk);
        mVideoview.setMediaController(mediacontroller);
        mVideoview.setVideoURI(video);

        mVideoview.requestFocus();
        mVideoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mVideoview.start();
            }
        });

        mVideoview.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                L.e("Could not play video, what " + what + ", extra " + extra + ", content_type " + mContentType
                        + ", and url " + mDownloadUrl);

                AlertDialog.Builder builder = new AlertDialog.Builder(AttachmentViewerActivity.this);
                builder.setMessage(R.string.error_please_try_again);
                builder.setCancelable(true);
                builder.setTitle(null);
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.setPositiveButton(R.string.rogerthat, new SafeDialogInterfaceOnClickListener() {
                    @Override
                    public void safeOnClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.create().show();
                return true;
            }
        });

    } else if (CONTENT_TYPE_PDF.equalsIgnoreCase(mContentType)) {
        WebSettings settings = mWebview.getSettings();
        settings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowUniversalAccessFromFileURLs(true);
        }

        mWebview.setWebViewClient(new WebViewClient() {

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (fileOnDisk.equals(url)) {
                    return null;
                }
                L.d("404: Expected: '" + fileOnDisk + "'\n Received: '" + url + "'");
                return new WebResourceResponse("text/plain", "UTF-8", null);
            }
        });
        try {
            mWebview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file="
                    + URLEncoder.encode(fileOnDisk, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            L.bug(uee);
        }
    } else {
        WebSettings settings = mWebview.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
        }
        settings.setBuiltInZoomControls(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);

        if (mContentType.toLowerCase(Locale.US).startsWith("image/")) {
            String html = "<html><head></head><body><img style=\"width: 100%;\" src=\"" + fileOnDisk
                    + "\"></body></html>";
            mWebview.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
        } else {
            mWebview.loadUrl(fileOnDisk);
        }
    }
    L.d("File on disk: " + fileOnDisk);
}

From source file:mgks.os.webview.MainActivity.java

@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" })
@Override// w  ww  . j a va  2s .  c o  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:org.apache.cordova.CordovaWebView.java

/**
 * Initialize webview./*from  w w  w .j  a va  2  s .c om*/
 */
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void setup() {

    this.setInitialScale(0);
    this.setVerticalScrollBarEnabled(false);
    this.requestFocusFromTouch();

    // Enable JavaScript
    WebSettings settings = this.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);

    //Set the nav dump for HTC 2.x devices (disabling for ICS/Jellybean)
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
        settings.setNavDump(true);

    //Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist
    //while we do this
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        settings.setAllowUniversalAccessFromFileURLs(true);
    // Enable database
    settings.setDatabaseEnabled(true);
    String databasePath = this.cordova.getActivity().getApplicationContext()
            .getDir("database", Context.MODE_PRIVATE).getPath();
    settings.setDatabasePath(databasePath);

    // Enable DOM storage
    settings.setDomStorageEnabled(true);

    // Enable built-in geolocation
    settings.setGeolocationEnabled(true);

    //Start up the plugin manager
    try {
        this.pluginManager = new PluginManager(this, this.cordova);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    exposeJsInterface();
}

From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java

@SuppressWarnings("deprecation")
@SuppressLint({ "SetJavaScriptEnabled", "Wakelock" })
private void displayBranding() {
    try {/*from   w  w w  .  j a va2s . c  o  m*/
        mServiceFriend = mFriendsPlugin.getStore().getExistingFriend(mServiceEmail);
        mBrandingResult = mMessagingPlugin.getBrandingMgr().prepareBranding(mBrandingKey, mServiceFriend, true);
        WebSettings settings = mBranding.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBlockNetworkImage(false);

        String fileOnDisk = "file://" + mBrandingResult.file.getAbsolutePath();
        if (mBrandingResult.contentType != null
                && AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(mBrandingResult.contentType)) {
            mIsHtmlContent = false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                settings.setAllowUniversalAccessFromFileURLs(true);
            }
            mBranding.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + fileOnDisk);
        } else {
            mIsHtmlContent = true;
            mBranding.loadUrl(fileOnDisk);
            mBranding.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            if (mBrandingResult.color != null) {
                mBranding.setBackgroundColor(mBrandingResult.color);
            }
        }
        mWakelockEnabled = mBrandingResult.wakelockEnabeld;
        L.d("wakelockEnabeld: " + mWakelockEnabled);
        if (mWakelockEnabled && mWakeLock == null) {
            mWakeLock = newWakeLock();
            L.d("Acquiring wakelock " + mWakeLock.hashCode());
            mWakeLock.acquire();
        } else if (mWakeLock != null && !mWakelockEnabled) {
            mWakeLock.release();
        }

    } catch (BrandingFailureException e) {
        UIUtils.showLongToast(this, getString(R.string.failed_to_show_action_screen));
        finish();
        mMessagingPlugin.getBrandingMgr().queue(mServiceFriend);
        L.e("Could not display menu item with screen branding.", e);
        return;
    }

}