Example usage for android.net Uri fromFile

List of usage examples for android.net Uri fromFile

Introduction

In this page you can find the example usage for android.net Uri fromFile.

Prototype

public static Uri fromFile(File file) 

Source Link

Document

Creates a Uri from a file.

Usage

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

private static void showMedia(final String localId, final Context ctx, final ProgressDialog dialog) {
    new AsyncTask<Void, Void, Boolean>() {

        private boolean noMedia = false;

        @Override/*  w w w .ja va2s .c o m*/
        protected Boolean doInBackground(Void... params) {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);

            Intent mediaPlayer = new Intent(Intent.ACTION_VIEW);

            if (file1.exists()) {
                mediaPlayer.setDataAndType(Uri.fromFile(file1), "image/*");
            } else if (file2.exists()) {
                mediaPlayer.setDataAndType(Uri.fromFile(file2), "video/*");

            } else {
                noMedia = true;
                return false;
            }
            ctx.startActivity(mediaPlayer);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            if (noMedia) {
                Toast.makeText(ctx.getApplicationContext(),
                        ctx.getApplicationContext().getText(R.string.no_media), Toast.LENGTH_SHORT).show();
                noMedia = false;
            }
        }

    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}

From source file:com.njlabs.amrita.aid.aums.AumsResourcesActivity.java

private void openFile(File file, String fileName) {
    Intent fileOpenIntent = new Intent(Intent.ACTION_VIEW);
    fileOpenIntent.setData(Uri.fromFile(file));
    Intent fileChooserIntent = Intent.createChooser(fileOpenIntent, "Open " + fileName + " with:");
    startActivity(fileChooserIntent);// w w w  .java 2 s  .c o m

}

From source file:com.dycody.android.idealnote.async.DataBackupIntentService.java

/**
  * Imports notes and notebooks from Springpad exported archive
  *// ww  w. j  a v a  2s.co m
  * @param intent
  */
synchronized private void importDataFromSpringpad(Intent intent) {
    String backupPath = intent.getStringExtra(EXTRA_SPRINGPAD_BACKUP);
    Importer importer = new Importer();
    try {
        importer.setZipProgressesListener(percentage -> mNotificationsHelper
                .setMessage(getString(com.dycody.android.idealnote.R.string.extracted) + " " + percentage + "%")
                .show());
        importer.doImport(backupPath);
        // Updating notification
        updateImportNotification(importer);
    } catch (ImportException e) {
        new NotificationsHelper(this)
                .createNotification(com.dycody.android.idealnote.R.drawable.ic_emoticon_sad_white_24dp,
                        getString(com.dycody.android.idealnote.R.string.import_fail) + ": " + e.getMessage(),
                        null)
                .setLedActive().show();
        return;
    }
    List<SpringpadElement> elements = importer.getSpringpadNotes();

    // If nothing is retrieved it will exit
    if (elements == null || elements.size() == 0) {
        return;
    }

    // These maps are used to associate with post processing notes to categories (notebooks)
    HashMap<String, Category> categoriesWithUuid = new HashMap<>();

    // Adds all the notebooks (categories)
    for (SpringpadElement springpadElement : importer.getNotebooks()) {
        Category cat = new Category();
        cat.setName(springpadElement.getName());
        cat.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
        DbHelper.getInstance().updateCategory(cat);
        categoriesWithUuid.put(springpadElement.getUuid(), cat);

        // Updating notification
        importedSpringpadNotebooks++;
        updateImportNotification(importer);
    }
    // And creates a default one for notes without notebook 
    Category defaulCategory = new Category();
    defaulCategory.setName("Springpad");
    defaulCategory.setColor(String.valueOf(Color.parseColor("#F9EA1B")));
    DbHelper.getInstance().updateCategory(defaulCategory);

    // And then notes are created
    Note note;
    Attachment mAttachment = null;
    Uri uri;
    for (SpringpadElement springpadElement : importer.getNotes()) {
        note = new Note();

        // Title
        note.setTitle(springpadElement.getName());

        // Content dependent from type of Springpad note
        StringBuilder content = new StringBuilder();
        content.append(
                TextUtils.isEmpty(springpadElement.getText()) ? "" : Html.fromHtml(springpadElement.getText()));
        content.append(
                TextUtils.isEmpty(springpadElement.getDescription()) ? "" : springpadElement.getDescription());

        // Some notes could have been exported wrongly
        if (springpadElement.getType() == null) {
            Toast.makeText(this, getString(com.dycody.android.idealnote.R.string.error), Toast.LENGTH_SHORT)
                    .show();
            continue;
        }

        if (springpadElement.getType().equals(SpringpadElement.TYPE_VIDEO)) {
            try {
                content.append(System.getProperty("line.separator"))
                        .append(springpadElement.getVideos().get(0));
            } catch (IndexOutOfBoundsException e) {
                content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
            }
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_TVSHOW)) {
            content.append(System.getProperty("line.separator"))
                    .append(TextUtils.join(", ", springpadElement.getCast()));
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOK)) {
            content.append(System.getProperty("line.separator")).append("Author: ")
                    .append(springpadElement.getAuthor()).append(System.getProperty("line.separator"))
                    .append("Publication date: ").append(springpadElement.getPublicationDate());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_RECIPE)) {
            content.append(System.getProperty("line.separator")).append("Ingredients: ")
                    .append(springpadElement.getIngredients()).append(System.getProperty("line.separator"))
                    .append("Directions: ").append(springpadElement.getDirections());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BOOKMARK)) {
            content.append(System.getProperty("line.separator")).append(springpadElement.getUrl());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_BUSINESS)
                && springpadElement.getPhoneNumbers() != null) {
            content.append(System.getProperty("line.separator")).append("Phone number: ")
                    .append(springpadElement.getPhoneNumbers().getPhone());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_PRODUCT)) {
            content.append(System.getProperty("line.separator")).append("Category: ")
                    .append(springpadElement.getCategory()).append(System.getProperty("line.separator"))
                    .append("Manufacturer: ").append(springpadElement.getManufacturer())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_WINE)) {
            content.append(System.getProperty("line.separator")).append("Wine type: ")
                    .append(springpadElement.getWine_type()).append(System.getProperty("line.separator"))
                    .append("Varietal: ").append(springpadElement.getVarietal())
                    .append(System.getProperty("line.separator")).append("Price: ")
                    .append(springpadElement.getPrice());
        }
        if (springpadElement.getType().equals(SpringpadElement.TYPE_ALBUM)) {
            content.append(System.getProperty("line.separator")).append("Artist: ")
                    .append(springpadElement.getArtist());
        }
        for (SpringpadComment springpadComment : springpadElement.getComments()) {
            content.append(System.getProperty("line.separator")).append(springpadComment.getCommenter())
                    .append(" commented at 0").append(springpadComment.getDate()).append(": ")
                    .append(springpadElement.getArtist());
        }

        note.setContent(content.toString());

        // Checklists
        if (springpadElement.getType().equals(SpringpadElement.TYPE_CHECKLIST)) {
            StringBuilder sb = new StringBuilder();
            String checkmark;
            for (SpringpadItem mSpringpadItem : springpadElement.getItems()) {
                checkmark = mSpringpadItem.getComplete()
                        ? it.feio.android.checklistview.interfaces.Constants.CHECKED_SYM
                        : it.feio.android.checklistview.interfaces.Constants.UNCHECKED_SYM;
                sb.append(checkmark).append(mSpringpadItem.getName())
                        .append(System.getProperty("line.separator"));
            }
            note.setContent(sb.toString());
            note.setChecklist(true);
        }

        // Tags
        String tags = springpadElement.getTags().size() > 0
                ? "#" + TextUtils.join(" #", springpadElement.getTags())
                : "";
        if (note.isChecklist()) {
            note.setTitle(note.getTitle() + tags);
        } else {
            note.setContent(note.getContent() + System.getProperty("line.separator") + tags);
        }

        // Address
        String address = springpadElement.getAddresses() != null ? springpadElement.getAddresses().getAddress()
                : "";
        if (!TextUtils.isEmpty(address)) {
            try {
                double[] coords = GeocodeHelper.getCoordinatesFromAddress(this, address);
                note.setLatitude(coords[0]);
                note.setLongitude(coords[1]);
            } catch (IOException e) {
                Log.e(Constants.TAG,
                        "An error occurred trying to resolve address to coords during Springpad import");
            }
            note.setAddress(address);
        }

        // Reminder
        if (springpadElement.getDate() != null) {
            note.setAlarm(springpadElement.getDate().getTime());
        }

        // Creation, modification, category
        note.setCreation(springpadElement.getCreated().getTime());
        note.setLastModification(springpadElement.getModified().getTime());

        // Image
        String image = springpadElement.getImage();
        if (!TextUtils.isEmpty(image)) {
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, image);
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + image);
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // Other attachments
        for (SpringpadAttachment springpadAttachment : springpadElement.getAttachments()) {
            // The attachment could be the image itself so it's jumped
            if (image != null && image.equals(springpadAttachment.getUrl()))
                continue;

            if (TextUtils.isEmpty(springpadAttachment.getUrl())) {
                continue;
            }

            // Tries first with online images
            try {
                File file = StorageHelper.createNewAttachmentFileFromHttp(this, springpadAttachment.getUrl());
                uri = Uri.fromFile(file);
                String mimeType = StorageHelper.getMimeType(uri.getPath());
                mAttachment = new Attachment(uri, mimeType);
            } catch (MalformedURLException e) {
                uri = Uri.parse(importer.getWorkingPath() + springpadAttachment.getUrl());
                mAttachment = StorageHelper.createAttachmentFromUri(this, uri, true);
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error retrieving Springpad online image");
            }
            if (mAttachment != null) {
                note.addAttachment(mAttachment);
            }
            mAttachment = null;
        }

        // If the note has a category is added to the map to be post-processed
        if (springpadElement.getNotebooks().size() > 0) {
            note.setCategory(categoriesWithUuid.get(springpadElement.getNotebooks().get(0)));
        } else {
            note.setCategory(defaulCategory);
        }

        // The note is saved
        DbHelper.getInstance().updateNote(note, false);
        ReminderHelper.addReminder(IdealNote.getAppContext(), note);

        // Updating notification
        importedSpringpadNotes++;
        updateImportNotification(importer);
    }

    // Delete temp data
    try {
        importer.clean();
    } catch (IOException e) {
        Log.w(Constants.TAG, "Springpad import temp files not deleted");
    }

    String title = getString(com.dycody.android.idealnote.R.string.data_import_completed);
    String text = getString(com.dycody.android.idealnote.R.string.click_to_refresh_application);
    createNotification(intent, this, title, text, null);
}

From source file:net.bluecarrot.lite.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // setup the sharedPreferences
    savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // if the app is being launched for the first time
    if (savedPreferences.getBoolean("first_run", true)) {
        //todo presentation
        // save the fact that the app has been started at least once
        savedPreferences.edit().putBoolean("first_run", false).apply();
    }//  w w  w .j  a  v a 2 s  . c om

    setContentView(R.layout.activity_main);//load the layout

    //**MOBFOX***//

    banner = (Banner) findViewById(R.id.banner);
    final Activity self = this;

    banner.setListener(new BannerListener() {
        @Override
        public void onBannerError(View view, Exception e) {
            //Toast.makeText(self, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerLoaded(View view) {
            //Toast.makeText(self, "banner loaded", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClosed(View view) {
            //Toast.makeText(self, "banner closed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerFinished(View view) {
            // Toast.makeText(self, "banner finished", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClicked(View view) {
            //Toast.makeText(self, "banner clicked", Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onCustomEvent(JSONArray jsonArray) {
            return false;
        }
    });

    banner.setInventoryHash(appHash);
    banner.load();

    // setup the refresh layout
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setColorSchemeResources(R.color.officialBlueFacebook, R.color.darkBlueSlimFacebookTheme);// set the colors
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    /** get a subject and text and check if this is a link trying to be shared */
    String sharedSubject = getIntent().getStringExtra(Intent.EXTRA_SUBJECT);
    String sharedUrl = getIntent().getStringExtra(Intent.EXTRA_TEXT);

    // if we have a valid URL that was shared by us, open the sharer
    if (sharedUrl != null) {
        if (!sharedUrl.equals("")) {
            // check if the URL being shared is a proper web URL
            if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) {
                // if it's not, let's see if it includes an URL in it (prefixed with a message)
                int startUrlIndex = sharedUrl.indexOf("http:");
                if (startUrlIndex > 0) {
                    // seems like it's prefixed with a message, let's trim the start and get the URL only
                    sharedUrl = sharedUrl.substring(startUrlIndex);
                }
            }
            // final step, set the proper Sharer...
            urlSharer = String.format("https://m.facebook.com/sharer.php?u=%s&t=%s", sharedUrl, sharedSubject);
            // ... and parse it just in case
            urlSharer = Uri.parse(urlSharer).toString();
            isSharer = true;
        }
    }

    // setup the webView
    webViewFacebook = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewFacebook);
    //fits images to screen

    if (isSharer) {//if is a share request
        webViewFacebook.loadUrl(urlSharer);//load the sharer url
        isSharer = false;
    } else
        goHome();//load homepage

    //        webViewFacebook.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
    //            public void onSwipeLeft() {
    //                webViewFacebook.loadUrl("javascript:try{document.querySelector('#messages_jewel > a').click();}catch(e){window.location.href='" +
    //                        getString(R.string.urlFacebookMobile) + "messages/';}");
    //            }
    //
    //        });

    //WebViewClient that is the client callback.
    webViewFacebook.setWebViewClient(new WebViewClient() {//advanced set up

        // when there isn't a connetion
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            String summary = "<h1 style='text-align:center; padding-top:15%; font-size:70px;'>"
                    + getString(R.string.titleNoConnection) + "</h1> <h3 "
                    + "style='text-align:center; padding-top:1%; font-style: italic;font-size:50px;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='font-size:30px; text-align:center; padding-top:80%; "
                    + "opacity: 0.3;'>" + getString(R.string.awards) + "</h5>";
            webViewFacebook.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page

            noConnectionError = true;
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
        }

        // when I click in a external link
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null || Uri.parse(url).getHost().endsWith("facebook.com")
                    || Uri.parse(url).getHost().endsWith("m.facebook.com") || url.contains(".gif")) {
                //url is ok
                return false;
            } else {
                if (Uri.parse(url).getHost().endsWith("fbcdn.net")) {
                    //TODO add the possibility to download and share directly

                    Toast.makeText(getApplicationContext(), getString(R.string.downloadOrShareWithBrowser),
                            Toast.LENGTH_LONG).show();
                    //TODO get bitmap from url

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

                //if the link doesn't contain 'facebook.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } //https://www.facebook.com/dialog/return/close?#_=_
        }

        //START management of loading
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //TODO when I push on messages, open messanger
            //                if(url!=null){
            //                    if (url.contains("soft=messages") || url.contains("facebook.com/messages")) {
            //                        Toast.makeText(getApplicationContext(),"Open Messanger",
            //                                Toast.LENGTH_SHORT).show();
            //                        startActivity(new Intent(getPackageManager().getLaunchIntentForPackage("com.facebook.orca")));//messanger
            //                    }
            //                }

            // show you progress image
            if (!swipeRefresh) {
                if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                    final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                    refreshItem.setActionView(R.layout.circular_progress_bar);
                }
            }
            swipeRefresh = false;
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                refreshItem.setActionView(null);
            }

            //load the css customizations
            String css = "";
            if (savedPreferences.getBoolean("pref_blackTheme", false)) {
                css += getString(R.string.blackCss);
            }
            if (savedPreferences.getBoolean("pref_fixedBar", true)) {

                css += getString(R.string.fixedBar);//get the first part

                int navbar = 0;//default value
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//get id
                if (resourceId > 0) {//if there is
                    navbar = getResources().getDimensionPixelSize(resourceId);//get the dimension
                }
                float density = getResources().getDisplayMetrics().density;
                int barHeight = (int) ((getResources().getDisplayMetrics().heightPixels - navbar - 44)
                        / density);

                css += ".flyout { max-height:" + barHeight + "px; overflow-y:scroll;  }";//without this doen-t scroll

            }
            if (savedPreferences.getBoolean("pref_hideSponsoredPosts", false)) {
                css += getString(R.string.hideSponsoredPost);
            }

            //apply the customizations
            webViewFacebook.loadUrl(
                    "javascript:function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = "
                            + "str; document.body.appendChild(node); } addStyleString('" + css + "');");

            //finish the load
            super.onPageFinished(view, url);

            //when the page is loaded, stop the refreshing
            swipeRefreshLayout.setRefreshing(false);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewFacebook.setWebChromeClient(new WebChromeClient() {
        //to the Geolocation
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            //todo notify when the gps is used
        }

        //to upload files
        //!!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
        // for >= Lollipop, all in one
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            /** Request permission for external storage access.
             *  If granted it's awesome and go on,
             *  otherwise just stop here and leave the method.
             */
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

                // create the file where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Toast.makeText(getApplicationContext(), "Error occurred while creating the File",
                            Toast.LENGTH_LONG).show();
                }

                // continue only if the file was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.chooseAnImage));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

            return true;
        }

        // creating image files (Lollipop only)
        private File createImageFile() throws IOException {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            if (!imageStorageDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                imageStorageDir.mkdirs();
            }

            // create an image file name
            imageStorageDir = new File(imageStorageDir + File.separator + "IMG_"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            return imageStorageDir;
        }

        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            mUploadMessage = uploadMsg;

            try {
                File imageStorageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        appDirectoryName);

                if (!imageStorageDir.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    imageStorageDir.mkdirs();
                }

                File file = new File(imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis()) + ".jpg");

                mCapturedImageURI = Uri.fromFile(file); // save to the private variable

                final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                //captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");

                Intent chooserIntent = Intent.createChooser(i, getString(R.string.chooseAnImage));
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });

                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), ("Camera Exception"), Toast.LENGTH_LONG).show();
            }
        }

        // openFileChooser for other Android versions

        /**
         * may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
         * https://code.google.com/p/android/issues/detail?id=62220
         * however newer versions of KitKat fixed it on some devices
         */
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

    });

    // OnLongClickListener for detecting long clicks on links and images
    // !!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
    webViewFacebook.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // activate long clicks on links and image links according to settings
            if (true) {
                WebView.HitTestResult result = webViewFacebook.getHitTestResult();
                if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE
                        || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    Message msg = linkHandler.obtainMessage();
                    webViewFacebook.requestFocusNodeHref(msg);
                    return true;
                }
            }
            return false;
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:io.strider.camera.CameraLauncher.java

/**
 * Called when the camera view exits.//from w  w w.jav a  2  s.  c  om
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
                    if (bitmap == null) {
                        // Try to get the bitmap from intent.
                        bitmap = (Bitmap) intent.getExtras().get("data");
                    }

                    // Double-check the bitmap.
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI || destType == NATIVE_URI) {
                    if (this.saveToPhotoAlbum) {
                        Uri inputUri = getUriFromMediaStore();
                        //Just because we have a media URI doesn't mean we have a real file, we need to make it
                        uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
                    } else {
                        uri = Uri.fromFile(
                                new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && !this.correctOrientation) {
                        writeUncompressedImage(uri);

                        this.callbackContext.success(uri.toString());
                    } else {
                        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileHelper.getRealPath(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.callbackContext.success(uri.toString());
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    //      // If retrieving photo from library
    //      else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
    //         if (resultCode == Activity.RESULT_OK) {
    //            Uri uri = intent.getData();
    //
    //            // If you ask for video or all media type you will automatically get back a file URI
    //            // and there will be no attempt to resize any returned data
    //            if (this.mediaType != PICTURE) {
    //               this.callbackContext.success(uri.toString());
    //            }
    //            else {
    //               // This is a special case to just return the path as no scaling,
    //               // rotating, nor compressing needs to be done
    //               if (this.targetHeight == -1 && this.targetWidth == -1 &&
    //                     (destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
    //                  this.callbackContext.success(uri.toString());
    //               } else {
    //                  String uriString = uri.toString();
    //                  // Get the path to the image. Makes loading so much easier.
    //                  String mimeType = FileHelper.getMimeType(uriString, this.cordova);
    //                  // If we don't have a valid image so quit.
    //                  if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
    //                     Log.d(LOG_TAG, "I either have a null image path or bitmap");
    //                     this.failPicture("Unable to retrieve path to picture!");
    //                     return;
    //                  }
    //                  Bitmap bitmap = null;
    //                  try {
    //                     bitmap = getScaledBitmap(uriString);
    //                  } catch (IOException e) {
    //                     e.printStackTrace();
    //                  }
    //                  if (bitmap == null) {
    //                     Log.d(LOG_TAG, "I either have a null image path or bitmap");
    //                     this.failPicture("Unable to create bitmap!");
    //                     return;
    //                  }
    //
    //                  if (this.correctOrientation) {
    //                     rotate = getImageOrientation(uri);
    //                     if (rotate != 0) {
    //                        Matrix matrix = new Matrix();
    //                        matrix.setRotate(rotate);
    //                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    //                     }
    //                  }
    //
    //                  // If sending base64 image back
    //                  if (destType == DATA_URL) {
    //                     this.processPicture(bitmap);
    //                  }
    //
    //                  // If sending filename back
    //                  else if (destType == FILE_URI || destType == NATIVE_URI) {
    //                     // Do we need to scale the returned file
    //                     if (this.targetHeight > 0 && this.targetWidth > 0) {
    //                        try {
    //                           // Create an ExifHelper to save the exif data that is lost during compression
    //                           String resizePath = getTempDirectoryPath() + "/resize.jpg";
    //                           // Some content: URIs do not map to file paths (e.g. picasa).
    //                           String realPath = FileHelper.getRealPath(uri, this.cordova);
    //                           ExifHelper exif = new ExifHelper();
    //                           if (realPath != null && this.encodingType == JPEG) {
    //                              try {
    //                                 exif.createInFile(realPath);
    //                                 exif.readExifData();
    //                                 rotate = exif.getOrientation();
    //                              } catch (IOException e) {
    //                                 e.printStackTrace();
    //                              }
    //                           }
    //
    //                           OutputStream os = new FileOutputStream(resizePath);
    //                           bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
    //                           os.close();
    //
    //                           // Restore exif data to file
    //                           if (realPath != null && this.encodingType == JPEG) {
    //                              exif.createOutFile(resizePath);
    //                              exif.writeExifData();
    //                           }
    //
    //                           // The resized image is cached by the app in order to get around this and not have to delete you
    //                           // application cache I'm adding the current system time to the end of the file url.
    //                           this.callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis());
    //                        } catch (Exception e) {
    //                           e.printStackTrace();
    //                           this.failPicture("Error retrieving image.");
    //                        }
    //                     }
    //                     else {
    //                        this.callbackContext.success(uri.toString());
    //                     }
    //                  }
    //                  if (bitmap != null) {
    //                     bitmap.recycle();
    //                     bitmap = null;
    //                  }
    //                  System.gc();
    //               }
    //            }
    //         }
    //         else if (resultCode == Activity.RESULT_CANCELED) {
    //            this.failPicture("Selection cancelled.");
    //         }
    //         else {
    //            this.failPicture("Selection did not complete!");
    //         }
    //      }
}

From source file:com.cm.android.beercellar.ui.ImageGridFragment.java

/**
 * @author anshu/*from w  ww . jav  a2  s .  co m*/
 */
public void takePhoto() throws IOException {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = Utils.createImageFile(getActivity());
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.e("takePhoto", ex.toString());
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            getActivity().getSharedPreferences(Utils.SHARED_PREF_NAME, Context.MODE_PRIVATE).edit()
                    .putString("IMAGE_NAME", photoFile.getName()).commit();
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

From source file:com.paramedic.mobshaman.fragments.AccionesDetalleServicioFragment.java

/**
 * Start the camera by dispatching a camera intent.
 *///w  w w . ja  va2  s  .c om
protected void dispatchTakePictureIntent(boolean isFinishingService) {

    // Check if there is a camera.
    Context context = getActivity();
    PackageManager packageManager = context.getPackageManager();
    if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false) {
        Toast.makeText(getActivity(), "This device does not have a camera.", Toast.LENGTH_SHORT).show();
        return;
    }

    // Camera exists? Then proceed...
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // Ensure that there's a camera activity to handle the intent
    DetalleServicioActivity activity = (DetalleServicioActivity) getActivity();
    if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
        // Create the File where the photo should go.
        // If you don't do this, you may get a crash in some devices.
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Toast toast = Toast.makeText(activity, "There was a problem saving the photo...",
                    Toast.LENGTH_SHORT);
            toast.show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri fileUri = Uri.fromFile(photoFile);
            activity.setCapturedImageURI(fileUri);
            activity.setCurrentPhotoPath(fileUri.getPath());
            activity.setIsFinishingService(isFinishingService);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, activity.getCapturedImageURI());

            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

From source file:com.richtodd.android.quiltdesign.app.BlockEditActivity.java

private Uri saveQuiltDesign() throws IOException, RepositoryException {

    BlockEditFragment fragment = getBlockEditFragment();
    PaperPiecedBlock block = fragment.getBlock();

    File file = new File(StorageUtility.getPublicFolder(), getCurrentBlockName() + ".quiltdesign");

    saveQuiltDesign(block, file);//ww  w  .j  a v  a2 s  .c o m

    Uri uri = Uri.fromFile(file);

    return uri;
}

From source file:io.ingame.squarecamera.CameraLauncher.java

/**
 * Applies all needed transformation to the image received from the camera.
 *
 * @param destType          In which form should we return the image
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 *//*from  w  ww. j a  v  a  2s .  c o  m*/
private void processResultFromCamera(int destType, Intent intent) throws IOException {
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.jpg");
            exif.readExifData();
            rotate = exif.getOrientation();
        } else if (this.encodingType == PNG) {
            exif.createInFile(getTempDirectoryPath() + "/.Pic.png");
            exif.readExifData();
            rotate = exif.getOrientation();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Bitmap bitmap = null;
    Uri uri = null;

    // If sending base64 image back
    if (destType == DATA_URL) {
        bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
        if (bitmap == null) {
            // Try to get the bitmap from intent.
            bitmap = (Bitmap) intent.getExtras().get("data");
        }

        // Double-check the bitmap.
        if (bitmap == null) {
            Log.d(LOG_TAG, "I either have a null image path or bitmap");
            this.failPicture("Unable to create bitmap!");
            return;
        }

        if (rotate != 0 && this.correctOrientation) {
            bitmap = getRotatedBitmap(rotate, bitmap, exif);
        }

        this.processPicture(bitmap);
        checkForDuplicateImage(DATA_URL);
    }

    // If sending filename back
    else if (destType == FILE_URI || destType == NATIVE_URI) {
        if (this.saveToPhotoAlbum) {
            Uri inputUri = getUriFromMediaStore();
            try {
                //Just because we have a media URI doesn't mean we have a real file, we need to make it
                uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
            } catch (NullPointerException e) {
                uri = null;
            }
        } else {
            uri = Uri.fromFile(new File(getTempDirectoryPath(), System.currentTimeMillis() + ".jpg"));
        }

        if (uri == null) {
            this.failPicture("Error capturing image - no media storage found.");
            return;
        }

        // If all this is true we shouldn't compress the image.
        if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                && !this.correctOrientation) {
            writeUncompressedImage(uri);

            this.callbackContext.success(uri.toString());
        } else {
            bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));

            if (rotate != 0 && this.correctOrientation) {
                bitmap = getRotatedBitmap(rotate, bitmap, exif);
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            if (this.encodingType == JPEG) {
                String exifPath;
                if (this.saveToPhotoAlbum) {
                    exifPath = FileHelper.getRealPath(uri, this.cordova);
                } else {
                    exifPath = uri.getPath();
                }
                exif.createOutFile(exifPath);
                exif.writeExifData();
            }
            if (this.allowEdit) {
                performCrop(uri);
            } else {
                // Send Uri back to JavaScript for viewing image
                this.callbackContext.success(uri.toString());
            }
        }
    } else {
        throw new IllegalStateException();
    }

    this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
    bitmap = null;
}

From source file:net.evecom.androidecssp.base.BaseWebActivity.java

/**
 * //from   w ww .ja v a 2  s  . c  om
 * 
 * 
 * @author Mars zhang
 * @created 2015-11-25 2:11:17
 * @param file
 * @return
 */
public Intent getFileIntent(File file) {
    // Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
    Uri uri = Uri.fromFile(file);
    String type = getMIMEType(file);
    Log.i("tag", "type=" + type);
    Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(uri, type);
    return intent;
}