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:de.sitewaerts.cordova.documentviewer.DocumentViewerPlugin.java

private void _open(String url, String contentType, String packageId, String activity,
        CallbackContext callbackContext, Bundle viewerOptions) throws JSONException {
    clearTempFiles();/*from w w  w.  j  a  v a2  s  . c  o m*/

    File file = getAccessibleFile(url);

    if (file != null && file.exists() && file.isFile()) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri path = Uri.fromFile(file);

            // @see http://stackoverflow.com/questions/2780102/open-another-application-from-your-own-intent
            intent.addCategory(Intent.CATEGORY_EMBED);
            intent.setDataAndType(path, contentType);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(this.getClass().getName(), viewerOptions);
            //activity needs fully qualified name here
            intent.setComponent(new ComponentName(packageId, packageId + "." + activity));

            this.callbackContext = callbackContext;
            this.cordova.startActivityForResult(this, intent, REQUEST_CODE_OPEN);

            // send shown event
            JSONObject successObj = new JSONObject();
            successObj.put(Result.STATUS, PluginResult.Status.OK.ordinal());
            PluginResult result = new PluginResult(PluginResult.Status.OK, successObj);
            // need to keep callback for close event
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put(Result.STATUS, PluginResult.Status.ERROR.ordinal());
            errorObj.put(Result.MESSAGE, "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put(Result.STATUS, PluginResult.Status.ERROR.ordinal());
        errorObj.put(Result.MESSAGE, "File not found");
        callbackContext.error(errorObj);
    }
}

From source file:org.openbmap.activities.DialogPreferenceCatalogs.java

@Override
public void onItemClicked(CatalogDownload catalog) {
    if (mCurrentCatalogDownloadId > -1) {
        Toast.makeText(getContext(), getContext().getString(R.string.other_download_active), Toast.LENGTH_LONG)
                .show();// w  w w  .j a v  a  2  s  .c o m
        return;
    }

    if (catalog.getUrl() == null) {
        Toast.makeText(getContext(), R.string.invalid_download, Toast.LENGTH_LONG).show();
        return;
    }

    Toast.makeText(getContext(), getContext().getString(R.string.downloading) + " " + catalog.getUrl(),
            Toast.LENGTH_LONG).show();
    // try to create directory
    final File folder = FileUtils.getCatalogFolder(getContext());
    Log.d(TAG, "Download destination" + folder.getAbsolutePath());

    boolean folderAccessible = false;
    if (folder.exists() && folder.canWrite()) {
        folderAccessible = true;
    }

    if (!folder.exists()) {
        folderAccessible = folder.mkdirs();
    }
    if (folderAccessible) {
        final String filename = catalog.getUrl().substring(catalog.getUrl().lastIndexOf('/') + 1);

        final File target = new File(folder.getAbsolutePath() + File.separator + filename);
        if (target.exists()) {
            Log.i(TAG, "Catalog file " + filename + " already exists. Overwriting..");
            target.delete();
        }

        try {
            // try to download to target. If target isn't below Environment.getExternalStorageDirectory(),
            // e.g. on second SD card a security exception is thrown
            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(catalog.getUrl()));
            request.setDestinationUri(Uri.fromFile(target));
            mCurrentCatalogDownloadId = mDownloadManager.enqueue(request);
        } catch (final SecurityException sec) {
            // download to temp dir and try to move to target later
            Log.w(TAG, "Security exception, can't write to " + target + ", using "
                    + getContext().getExternalCacheDir());
            final File tempFile = new File(getContext().getExternalCacheDir() + File.separator + filename);

            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(catalog.getUrl()));
            request.setDestinationUri(Uri.fromFile(tempFile));
            mCurrentCatalogDownloadId = mDownloadManager.enqueue(request);
            getDialog().dismiss();
        }
    } else {
        Toast.makeText(getContext(), R.string.error_save_file_failed, Toast.LENGTH_SHORT).show();
    }
    getDialog().dismiss();
}

From source file:org.openbmap.activities.DialogPreferenceMaps.java

@Override
public void onItemClicked(MapDownload map) {
    if (mCurrentMapDownloadId > -1) {
        Toast.makeText(getContext(), getContext().getString(R.string.other_download_active), Toast.LENGTH_LONG)
                .show();//from w ww .ja v  a  2  s .  c o  m
        return;
    }

    if (map.getUrl() == null) {
        Toast.makeText(getContext(), R.string.invalid_download, Toast.LENGTH_LONG).show();
        return;
    }

    Toast.makeText(getContext(), getContext().getString(R.string.downloading) + " " + map.getUrl(),
            Toast.LENGTH_LONG).show();
    // try to create directory
    final File folder = FileUtils.getMapFolder(getContext());
    Log.d(TAG, "Download destination" + folder.getAbsolutePath());

    boolean folderAccessible = false;
    if (folder.exists() && folder.canWrite()) {
        folderAccessible = true;
    }

    if (!folder.exists()) {
        folderAccessible = folder.mkdirs();
    }
    if (folderAccessible) {
        final String filename = map.getUrl().substring(map.getUrl().lastIndexOf('/') + 1);

        final File target = new File(folder.getAbsolutePath() + File.separator + filename);
        if (target.exists()) {
            Log.i(TAG, "Map file " + filename + " already exists. Overwriting..");
            target.delete();
        }

        try {
            // try to download to target. If target isn't below Environment.getExternalStorageDirectory(),
            // e.g. on second SD card a security exception is thrown
            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(map.getUrl()));
            request.setDestinationUri(Uri.fromFile(target));
            mCurrentMapDownloadId = mDownloadManager.enqueue(request);
        } catch (final SecurityException sec) {
            // download to temp dir and try to move to target later
            Log.w(TAG, "Security exception, can't write to " + target + ", using "
                    + getContext().getExternalCacheDir());
            final File tempFile = new File(getContext().getExternalCacheDir() + File.separator + filename);

            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(map.getUrl()));
            request.setDestinationUri(Uri.fromFile(tempFile));
            mCurrentMapDownloadId = mDownloadManager.enqueue(request);

            getDialog().dismiss();
        }
    } else {
        Toast.makeText(getContext(), R.string.error_save_file_failed, Toast.LENGTH_SHORT).show();
    }
    getDialog().dismiss();
}

From source file:com.bt.download.android.gui.util.UIUtils.java

/**
 * Opens the given file with the default Android activity for that File and
 * mime type./*w  w w.  j  a  v  a  2  s.c  om*/
 * 
 * @param filePath
 * @param mime
 */
public static void openFile(Context context, String filePath, String mime) {
    try {
        if (!openAudioInternal(filePath)) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.fromFile(new File(filePath)), mime);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);

            if (mime != null && mime.contains("video")) {
                if (MusicUtils.isPlaying()) {
                    MusicUtils.playOrPause();
                }
                UXStats.instance().log(UXAction.LIBRARY_VIDEO_PLAY);
            }
        }
    } catch (Throwable e) {
        UIUtils.showShortMessage(context, R.string.cant_open_file);
        Log.e(TAG, "Failed to open file: " + filePath, e);
    }
}

From source file:com.dwdesign.tweetings.activity.ComposeActivity.java

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {

    switch (requestCode) {
    case REQUEST_SCHEDULE_DATE: {
        if (resultCode == Activity.RESULT_OK) {
            Bundle bundle = intent.getExtras();
            mScheduleDate = bundle.getString(INTENT_KEY_SCHEDULE_DATE_TIME);
        } else {//ww w.  java2  s.c o m
            if (mScheduleDate != null) {
                mScheduleDate = null;
            }
        }
        setMenu();
        break;
    }
    case REQUEST_TAKE_PHOTO: {
        if (resultCode == Activity.RESULT_OK) {
            final File file = new File(mImageUri.getPath());
            if (file.exists()) {
                mIsImageAttached = false;
                mIsPhotoAttached = true;
                mImageThumbnailPreview.setVisibility(View.VISIBLE);
                reloadAttachedImageThumbnail(file);
            } else {
                mIsPhotoAttached = false;
            }
            setMenu();
            boolean isAutoUpload = mPreferences.getBoolean(PREFERENCE_KEY_AUTO_UPLOAD, false);
            if (!isNullOrEmpty(mUploadProvider) && mIsPhotoAttached && isAutoUpload) {
                postMedia();
            }
        }
        break;
    }
    case REQUEST_PICK_IMAGE: {
        if (resultCode == Activity.RESULT_OK) {
            final Uri uri = intent.getData();
            final File file = uri == null ? null : new File(getImagePathFromUri(this, uri));
            if (file != null && file.exists()) {
                mImageUri = Uri.fromFile(file);
                mIsPhotoAttached = false;
                mIsImageAttached = true;
                mImageThumbnailPreview.setVisibility(View.VISIBLE);
                reloadAttachedImageThumbnail(file);
            } else {
                mIsImageAttached = false;
            }
            setMenu();
            boolean isAutoUpload = mPreferences.getBoolean(PREFERENCE_KEY_AUTO_UPLOAD, false);
            if (!isNullOrEmpty(mUploadProvider) && mIsImageAttached && isAutoUpload) {
                postMedia();
            }
        }
        break;
    }
    case REQUEST_SELECT_ACCOUNT: {
        if (resultCode == Activity.RESULT_OK) {
            final Bundle bundle = intent.getExtras();
            if (bundle == null) {
                break;
            }
            final long[] account_ids = bundle.getLongArray(INTENT_KEY_IDS);
            if (account_ids != null) {
                mAccountIds = account_ids;
                if (mInReplyToStatusId <= 0 && !Intent.ACTION_SEND.equals(getIntent().getAction())) {
                    final SharedPreferences.Editor editor = mPreferences.edit();
                    editor.putString(PREFERENCE_KEY_COMPOSE_ACCOUNTS,
                            ArrayUtils.toString(mAccountIds, ',', false));
                    editor.commit();
                }
                mColorIndicator.setColor(getAccountColors(this, account_ids));
            }
        }
        break;
    }
    case REQUEST_EDIT_IMAGE: {
        if (resultCode == Activity.RESULT_OK) {
            final Uri uri = intent.getData();
            final File file = uri == null ? null : new File(getImagePathFromUri(this, uri));
            if (file != null && file.exists()) {
                mImageUri = Uri.fromFile(file);
                reloadAttachedImageThumbnail(file);
            } else {
                break;
            }
            setMenu();
        }
        break;
    }
    case REQUEST_EXTENSION_COMPOSE: {
        if (resultCode == Activity.RESULT_OK) {
            final Bundle extras = intent.getExtras();
            if (extras == null) {
                break;
            }
            final String text = extras.getString(INTENT_KEY_TEXT);
            final String append = extras.getString(INTENT_KEY_APPEND_TEXT);
            if (text != null) {
                mEditText.setText(text);
                mText = parseString(mEditText.getText());
            } else if (append != null) {
                mEditText.append(append);
                mText = parseString(mEditText.getText());
            }
        }
        break;
    }
    case ACTION_REQUEST_FEATHER:
        if (resultCode == RESULT_OK) {
            final Uri uri = intent.getData();
            final File file = uri == null ? null : new File(getImagePathFromUri(this, uri));
            if (file != null && file.exists()) {
                mImageUri = Uri.fromFile(file);
                reloadAttachedImageThumbnail(file);
            } else {
                break;
            }
            setMenu();
        }
        break;
    }

}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Take a picture with the camera.//w ww  .  j  a  va  2s .  c om
 * When an image is captured or the camera view is cancelled, the result is returned
 * in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult.
 *
 * The image can either be returned as a base64 string or a URI that points to the file.
 * To display base64 string in an img tag, set the source to:
 *      img.src="data:image/jpeg;base64,"+result;
 * or to display URI in an img tag
 *      img.src=result;
 *
 * @param quality           Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
 * @param returnType        Set the type of image to return.
 */
public void takePicture(int returnType, int encodingType) {
    // Save the number of images currently on disk for later
    this.numPics = queryImgDB(whichContentStore()).getCount();

    // Display camera
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

    // Specify file so that large image is captured and returned
    File photo = createCaptureFile(encodingType);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    this.imageUri = Uri.fromFile(photo);

    if (this.activity != null) {
        this.activity.startActivityForResult(intent, (CAMERA + 1) * 16 + returnType + 1);
    }
    //        else
    //            LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
}

From source file:com.almarsoft.GroundhogReader.MessageActivity.java

protected void attachClicked(final String attachcode) {

    HashMap<String, String> tmpattachPart = null;
    String tmpmd5 = null;//from w  w w. ja v  a2 s. c om

    for (HashMap<String, String> part : mMimePartsVector) {
        tmpmd5 = part.get("md5");
        if (tmpmd5.equals(attachcode)) {
            tmpattachPart = part;
            break;
        }
    }

    final String md5 = tmpmd5;
    final HashMap<String, String> attachPart = tmpattachPart;

    if (attachPart != null && md5 != null) {

        new AlertDialog.Builder(this).setTitle(getString(R.string.attachment))
                .setMessage(getString(R.string.open_save_attach_question))
                .setPositiveButton(getString(R.string.open), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction(android.content.Intent.ACTION_VIEW);
                        File attFile = new File(UsenetConstants.EXTERNALSTORAGE + "/" + UsenetConstants.APPNAME
                                + "/" + UsenetConstants.ATTACHMENTSDIR + "/" + mGroup, md5);
                        Uri attachUri = Uri.fromFile(attFile);
                        intent.setDataAndType(attachUri, attachPart.get("type"));
                        startActivity(intent);
                    }
                }).setNegativeButton(getString(R.string.save), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                        try {
                            String finalPath = FSUtils.saveAttachment(md5, mGroup, attachPart.get("name"));
                            Toast.makeText(MessageActivity.this, getString(R.string.saved_to) + finalPath,
                                    Toast.LENGTH_LONG).show();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(MessageActivity.this,
                                    getString(R.string.could_not_save_colon) + e.toString(), Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                }).show();
    }
}

From source file:com.frostwire.android.gui.util.UIUtils.java

public static Uri getFileUri(Context context, String filePath, boolean useFileProvider) {
    return useFileProvider
            ? FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider",
                    new File(filePath))
            : Uri.fromFile(new File(filePath));
}

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

private Uri savePDF(RenderStyles renderStyle) throws IOException {

    QuiltEditFragment fragment = getQuiltEditFragment();
    Quilt quilt = fragment.getQuilt();//from   w  w w  .  j  ava  2 s . c  om

    File file = new File(StorageUtility.getPublicFolder(), getCurrentQuiltName() + ".pdf");

    savePDF(quilt, file, renderStyle, getCurrentQuiltName());

    Uri uri = Uri.fromFile(file);

    return uri;
}

From source file:org.mobisocial.corral.CorralDownloadClient.java

private Uri getFileOverLan(DbIdentity user, DbObj obj, CorralDownloadFuture future,
        DownloadProgressCallback callback) throws IOException {
    DownloadChannel channel = DownloadChannel.LAN;
    callback.onProgress(DownloadState.PREPARING_CONNECTION, channel, 0);
    InputStream in = null;/* www.j ava2s  .c o  m*/
    OutputStream out = null;
    try {
        // Remote
        String ip = getUserLanIp(mContext, user);
        Uri remoteUri = uriForLanContent(ip, obj);

        if (DBG) {
            Log.d(TAG, "Attempting to pull lan file " + remoteUri);
        }

        HttpClient http = new DefaultHttpClient();
        HttpGet get = new HttpGet(remoteUri.toString());
        HttpResponse response = http.execute(get);
        long contentLength = response.getEntity().getContentLength();

        File localFile = localFileForContent(obj, false);
        if (!localFile.exists()) {
            if (future.isCancelled()) {
                throw new IOException("User error");
            }
            localFile.getParentFile().mkdirs();
            try {
                in = response.getEntity().getContent();
                out = new FileOutputStream(localFile);
                byte[] buf = new byte[1024];
                int len;

                callback.onProgress(DownloadState.TRANSFER_IN_PROGRESS, channel, 0);
                int read = 0;
                int progress = 0;
                while (!future.isCancelled() && (len = in.read(buf)) > 0) {
                    read += len;
                    if (contentLength > 0) {
                        int newProgress = Math.round(100f * read / contentLength);
                        if (progress != newProgress) {
                            progress = newProgress;
                            callback.onProgress(DownloadState.TRANSFER_IN_PROGRESS, channel, progress);
                        }
                    }
                    out.write(buf, 0, len);
                }
                if (future.isCancelled()) {
                    throw new IOException("user cancelled");
                }
                if (DBG)
                    Log.d(TAG, "successfully fetched content over lan");
                callback.onProgress(DownloadState.TRANSFER_COMPLETE, channel, DownloadProgressCallback.SUCCESS);
            } catch (IOException e) {
                if (DBG)
                    Log.d(TAG, "failed to get content from lan");
                callback.onProgress(DownloadState.TRANSFER_COMPLETE, channel, DownloadProgressCallback.FAILURE);
                if (localFile.exists()) {
                    localFile.delete();
                }
                throw e;
            }
        }

        return Uri.fromFile(localFile);
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        } catch (IOException e) {
            Log.e(TAG, "failed to close handle on get corral content", e);
        }
    }
}