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:com.remobile.file.Filesystem.java

public JSONObject makeEntryForFile(File file) {
    return makeEntryForNativeUri(Uri.fromFile(file));
}

From source file:io.github.pwlin.cordova.plugins.fileopener2.FileOpener2.java

private void _open(String fileArg, String contentType, CallbackContext callbackContext) throws JSONException {
    String fileName = "";
    try {/*from  w  ww  . j a va 2 s.  c o m*/
        CordovaResourceApi resourceApi = webView.getResourceApi();
        Uri fileUri = resourceApi.remapUri(Uri.parse(fileArg));
        fileName = this.stripFileProtocol(fileUri.toString());
    } catch (Exception e) {
        fileName = fileArg;
    }
    File file = new File(fileName);
    if (file.exists()) {
        try {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= 24) {

                Context context = cordova.getActivity().getApplicationContext();
                path = FileProvider.getUriForFile(context,
                        cordova.getActivity().getPackageName() + ".opener.provider", file);
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                List<ResolveInfo> infoList = context.getPackageManager().queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : infoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, path,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            } else {
                intent.setDataAndType(path, contentType);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }
            /*
             * @see
             * http://stackoverflow.com/questions/14321376/open-an-activity-from-a-cordovaplugin
             */
            cordova.getActivity().startActivity(intent);
            //cordova.getActivity().startActivity(Intent.createChooser(intent,"Open File in..."));
            callbackContext.success();
        } catch (android.content.ActivityNotFoundException e) {
            JSONObject errorObj = new JSONObject();
            errorObj.put("status", PluginResult.Status.ERROR.ordinal());
            errorObj.put("message", "Activity not found: " + e.getMessage());
            callbackContext.error(errorObj);
        }
    } else {
        JSONObject errorObj = new JSONObject();
        errorObj.put("status", PluginResult.Status.ERROR.ordinal());
        errorObj.put("message", "File not found");
        callbackContext.error(errorObj);
    }
}

From source file:com.exercise.AndroidClient.RecvFrom.java

private Uri getDestFileUri() throws IOException {

    // map "music" to Environment.DIRECTORY_MUSIC 
    String destDir = destDirTypes.get(destinationType);
    if (destDir == null)
        throw new IllegalArgumentException("Invalid destination dir type : " + destinationType);

    // get the public 'standard directory', ie Download, Music etc
    File dir = Environment.getExternalStoragePublicDirectory(destDir);

    // add any subdir asked by caller & create dir struct upto the subdir if required
    dir = new File(dir, subDir);
    if (!dir.exists() || !dir.isDirectory()) {
        if (!dir.mkdirs())
            throw new IOException("Failed to create directories : " + dir.toString());
    }//ww w  . j  a  v  a 2s  .co m

    // the full path to the file
    File path = new File(dir, filename);
    return Uri.fromFile(path);
}

From source file:com.tuxpan.foregroundvideocapture.CaptureFG.java

/**
 * Sets up an intent to capture video. Result handled by onActivityResult()
 *//*from   w  w w  . j  a v  a 2  s.co  m*/
private void captureVideo(int duration) {
    // Intent intent = new
    // Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
    //
    // if(Build.VERSION.SDK_INT > 7){
    // intent.putExtra("android.intent.extra.durationLimit", duration);
    // }

    Intent intent = new Intent(this.cordova.getActivity().getApplicationContext(), RecorderActivity.class);
    intent.putExtra("android.intent.extra.durationLimit", duration);
    File video = new File(getTempDirectoryPath(), "video.3gp");
    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(video));
    this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
}

From source file:at.wada811.utils.IntentUtils.java

/**
 * Intent??// w w w  .  j  a va2  s.c  om
 *
 * @param intent
 * @param file
 * @return
 */
public static Intent addFile(Intent intent, File file) {
    return IntentUtils.addFile(intent, Uri.fromFile(file), MediaUtils.getMimeType(file));
}

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

/**
 * Returns a uri for the locally available content or null
 * if the content is not available locally.
 *//*  w ww.  ja  va 2 s .  com*/
public Uri getAvailableContentUri(DbObj obj) {
    if (!fileAvailableLocally(obj)) {
        return null;
    }
    if (mObjectManager.isObjectFromLocalDevice(obj.getLocalId())) {
        try {
            String uriString = obj.getJson().getString(OBJ_LOCAL_URI);
            return Uri.parse(uriString);
        } catch (Exception e) {
            return null;
        }
    }
    return Uri.fromFile(localFileForContent(obj, false));
}

From source file:de.appplant.cordova.plugin.notification.Asset.java

/**
 * The URI for a file.//from w ww  . j a  v a2  s  .  c  o m
 * 
 * @param path
 *            The given absolute path
 * 
 * @return The URI pointing to the given path
 */
private Uri getUriForAbsolutePath(String path) {
    String absPath = path.replaceFirst("file://", "");
    File file = new File(absPath);
    if (!file.exists()) {
        Log.e("Asset", "File not found: " + file.getAbsolutePath());
        return Uri.EMPTY;
    }
    return Uri.fromFile(file);
}

From source file:com.blork.anpod.util.BitmapUtils.java

public static BitmapResult fetchImage(Context context, Picture picture, int desiredWidth, int desiredHeight) {

    // First compute the cache key and cache file path for this URL
    File cacheFile = null;//from   ww  w  . j  av  a 2s . c  o m
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        Log.d("APOD", "creating cache file");
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        if (prefs.getBoolean("archive", false)) {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "APOD"
                    + File.separator + toSlug(picture.title) + ".jpg");
        } else {
            cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android"
                    + File.separator + "data" + File.separator + "com.blork.anpod" + File.separator + "cache"
                    + File.separator + toSlug(picture.title) + ".jpg");
        }
    } else {
        Log.d("APOD", "SD card not mounted");
        Log.d("APOD", "creating cache file");
        cacheFile = new File(context.getCacheDir() + File.separator + toSlug(picture.title) + ".jpg");
    }

    if (cacheFile != null && cacheFile.exists()) {
        Log.d("APOD", "Cache file exists, using it.");
        try {
            Bitmap bitmap = decodeStream(new FileInputStream(cacheFile), desiredWidth, desiredHeight);
            return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
        } catch (FileNotFoundException e) {
        }
    }

    try {
        Log.d("APOD", "Not cached, fetching");
        BitmapUtils.manageCache(toSlug(picture.title), context);
        // TODO: check for HTTP caching headers
        final HttpClient httpClient = SyncUtils.getHttpClient(context.getApplicationContext());
        final HttpResponse resp = httpClient.execute(new HttpGet(picture.getFullSizeImageUrl()));
        final HttpEntity entity = resp.getEntity();

        final int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK || entity == null) {
            return null;
        }

        final byte[] respBytes = EntityUtils.toByteArray(entity);

        Log.d("APOD", "Writing cache file " + cacheFile.getName());
        try {
            cacheFile.getParentFile().mkdirs();
            cacheFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(cacheFile);
            fos.write(respBytes);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        } catch (IOException e) {
            Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e);
        }

        // Decode the bytes and return the bitmap.
        Log.d("APOD", "Reiszing bitmap image");

        Bitmap bitmap = decodeStream(new ByteArrayInputStream(respBytes), desiredWidth, desiredHeight);
        Log.d("APOD", "Returning bitmap image");
        return new BitmapResult(bitmap, Uri.fromFile(cacheFile));
    } catch (Exception e) {
        Log.d("APOD", "Problem while loading image: " + e.toString(), e);
    }

    return null;
}

From source file:com.whamads.nativecamera.NativeCameraLauncher.java

public void takePicture() {
    // Save the number of images currently on disk for later
    Intent intent = new Intent(this.cordova.getActivity().getApplicationContext(), CameraActivity.class);
    this.photo = createCaptureFile();
    this.imageUri = Uri.fromFile(photo);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, this.imageUri);
    this.cordova.startActivityForResult((CordovaPlugin) this, intent, 1);
}

From source file:com.amo.meer.APPVersion.java

private void update() {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SAVENAME)),
            "application/vnd.android.package-archive");
    context.startActivity(intent);//from www .  j  av a 2 s.co  m
}