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:Main.java

/**
 * Save a media in the downloads directory and offer to open it with a third party application.
 * @param activity the activity/*from www  . jav a2 s. com*/
 * @param savedMediaPath the media path
 * @param mimeType the media mime type.
 */
public static void openMedia(final Activity activity, final String savedMediaPath, final String mimeType) {
    if ((null != activity) && (null != savedMediaPath)) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = new File(savedMediaPath);
                    Intent intent = new Intent();
                    intent.setAction(android.content.Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), mimeType);
                    activity.startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(activity, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                }
            }
        });
    }
}

From source file:Main.java

/**
 * @param path the absolute destination path
 *///from ww  w. j  a va  2s .c  o m
static long enqueue(DownloadManager dm, String uri, String path) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri));

    /* Unfortunately, we cannot use the simpler "ExternalPublicDir"
       Android feature, because on some Samsung products, we need to
       explicitly use the "external_sd" mount instead of the built-in
       storage.  Here, we must use whatever was returned by
       FindDataPath() in LocalPath.cpp. */
    //request.setDestinationInExternalPublicDir("XCSoarData", path);
    request.setDestinationUri(Uri.fromFile(new File(path)));

    request.setAllowedOverRoaming(false);
    request.setShowRunningNotification(true);
    return dm.enqueue(request);
}

From source file:Main.java

public static Bitmap saveBitmapToFile(Activity activity, Bitmap bitmap) {
    String mPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File imageFile = new File(mPath);
    boolean create = imageFile.mkdirs();
    boolean canWrite = imageFile.canWrite();
    Calendar cal = Calendar.getInstance();
    String date = cal.get(Calendar.YEAR) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.DATE);

    String filename = null;// www .  j  a v  a 2  s  . co m
    int i = 0;
    while (imageFile.exists()) {
        i++;
        filename = date + "_mandelbrot" + i + ".png";
        imageFile = new File(mPath, filename);
        boolean canWrite2 = imageFile.canWrite();

    }

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        /*resultB*/bitmap.compress(CompressFormat.PNG, 90, bos);
        byte[] bitmapdata = bos.toByteArray();

        //write the bytes in file
        FileOutputStream fos = new FileOutputStream(imageFile);
        fos.write(bitmapdata);
        fos.flush();
        fos.close();

        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(imageFile));
        activity.sendBroadcast(intent);

        displaySuccesToast(activity);
    } catch (FileNotFoundException e) {
        displayFileError(activity);
        e.printStackTrace();
    } catch (IOException e) {
        displayFileError(activity);
        e.printStackTrace();
    }
    return bitmap;
}

From source file:Main.java

protected static Uri scaleDown(Uri imageUri, int targetSize, Context context) {
    System.gc();// ww  w.  j  a v  a2 s  .c  om
    String imagePath = getImagePath(imageUri, context);
    Bitmap currentImage = BitmapFactory.decodeFile(imagePath);

    int targetWidth = targetSize;
    int targetHeight = targetSize;

    int width = currentImage.getWidth();
    int height = currentImage.getHeight();

    if (width < targetWidth || height < targetHeight) {
        currentImage.recycle();
        currentImage = null;
        System.gc();
        return Uri.parse(imageUri.toString());
    }

    height = (int) (height * (float) targetWidth / width);

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(currentImage, targetWidth, height, false);

    if (currentImage != scaledBitmap) {
        currentImage.recycle();
        currentImage = null;
    }
    System.gc();
    File imageFile;
    try {
        imageFile = new File(context.getCacheDir(), "vumatch-upload-00.jpeg");
        FileOutputStream output;

        output = new FileOutputStream(imageFile);
        boolean result = scaledBitmap.compress(CompressFormat.JPEG, 90, output);
        if (result) {
            scaledBitmap.recycle();
            scaledBitmap = null;
            return Uri.fromFile(imageFile);
        } else {
            return null;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:MainActivity.java

private Uri createFileURI() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(System.currentTimeMillis());
    String fileName = "PHOTO_" + timeStamp + ".jpg";
    return Uri.fromFile(
            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName));
}

From source file:Main.java

/** 
 * Create a file Uri for saving a recorded selfie
 */// w w  w. j  a va2  s  . co  m
@SuppressLint("SimpleDateFormat")
public static Uri getRecordedGhostMySelfieUri(Context context) {

    // Check to see if external SDCard is mounted or not.
    if (isExternalStorageWritable()) {
        // Create a path where we will place our recorded selfie in
        // the user's public DCIM directory. Note that you should
        // be careful about what you place here, since the user
        // often manages these files.
        final File ghostmyselfieStorageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

        // Create the storage directory if it does not exist
        if (!ghostmyselfieStorageDir.exists()) {
            if (!ghostmyselfieStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a TimeStamp for the selfie file.
        final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        // Create a selfie file name from the TimeStamp.
        final File ghostmyselfieFile = new File(
                ghostmyselfieStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

        // Always notify the MediaScanners after storing
        // the GhostMySelfie, so that it is immediately available to
        // the user.
        notifyMediaScanners(context, ghostmyselfieFile);

        //Return Uri from GhostMySelfie file.
        return Uri.fromFile(ghostmyselfieFile);

    } else
        //Return null if no SDCard is mounted.
        return null;
}

From source file:Main.java

public static Bitmap decodeSampledBitmapFromFile(Resources res, ContentResolver contentResolver, File file,
        int reqWidthInPixel, int reqHeightInPixel) throws IOException {

    Bitmap bitmap;//  w  w w.j ava  2  s .com
    AssetFileDescriptor fileDescriptor;

    fileDescriptor = contentResolver.openAssetFileDescriptor(Uri.fromFile(file), "r");

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidthInPixel, reqHeightInPixel);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
    fileDescriptor.close();
    return bitmap;
}

From source file:Main.java

/**
 * Show a level/*  w  w  w .j a v a2  s .co  m*/
 * 
 * @param context The context
 * @param level The level
 */
public static void showLevel(Context context, int level) {
    String filename;
    switch (level) {
    case 1: {
        filename = "ground_floor.png";
        break;
    }
    case 2: {
        filename = "talks_floor.png";
        break;
    }

    default: {
        return;
    }
    }
    File f = new File(context.getFilesDir() + "/" + filename);
    try {
        if (f.exists() == false) {
            InputStream is = context.getAssets().open(filename);
            FileOutputStream fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            // write the stream to file
            fos.write(buffer, 0, buffer.length);
            fos.close();
            is.close();
        }

        // Prepare the intent
        //TODO - create an activity for this instead. Internal viewers might be quite heavy
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(f), "image/png");
        context.startActivity(intent);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.theelix.libreexplorer.FileManager.java

/**
 * This method chooses the appropriate Apps and Open the file
 *
 * @param file The target file/*from   ww  w. jav  a2s  .  c  o m*/
 */
public static void openFile(File file) {
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        String mimeType = FileUtilties.getMimeType(uri);
        if (mimeType == null) {
            mimeType = "*/*";
        }
        intent.setDataAndType(uri, mimeType);
        mContext.startActivity(Intent.createChooser(intent, null));
    } catch (ActivityNotFoundException e) {
        //Activity is not found so App'll start an intent with generic Mimetype
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "*/*");
        mContext.startActivity(Intent.createChooser(intent, null));
    }

}

From source file:com.phonegap.plugins.openfilewithexternalapp.OpenFileWithExternalApp.java

public PluginResult execute(String action, JSONArray args, String callbackId) {

    try {/* w  ww .  jav  a 2  s  .c  o  m*/

        String filePath = args.getString(0);

        Intent intent = new Intent();

        intent.setAction(android.content.Intent.ACTION_VIEW);

        File fileToOpen = new File(filePath);

        MimeTypeMap mime = MimeTypeMap.getSingleton();

        String extension = fileToOpen.getName().substring(fileToOpen.getName().lastIndexOf(".") + 1)
                .toLowerCase();

        String type = mime.getMimeTypeFromExtension(extension);

        intent.setAction(Intent.ACTION_VIEW);

        Uri uri = Uri.fromFile(fileToOpen);

        intent.setDataAndType(uri, type);

        this.ctx.startActivity(intent);
    }

    catch (JSONException e) {

        e.printStackTrace();

    }

    PluginResult mPlugin = new PluginResult(PluginResult.Status.NO_RESULT);

    return mPlugin;
}