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.AssetFilesystem.java

@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
    if (!"file".equals(inputURL.getScheme())) {
        return null;
    }/* w w w .ja  va  2 s . c  o m*/
    File f = new File(inputURL.getPath());
    // Removes and duplicate /s (e.g. file:///a//b/c)
    Uri resolvedUri = Uri.fromFile(f);
    String rootUriNoTrailingSlash = rootUri.getEncodedPath();
    rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
    if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
        return null;
    }
    String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
    // Strip leading slash
    if (!subPath.isEmpty()) {
        subPath = subPath.substring(1);
    }
    Uri.Builder b = new Uri.Builder().scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL).authority("localhost")
            .path(name);
    if (!subPath.isEmpty()) {
        b.appendEncodedPath(subPath);
    }
    if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
        // Add trailing / for directories.
        b.appendEncodedPath("");
    }
    return LocalFilesystemURL.parse(b.build());
}

From source file:com.ushahidi.android.app.UshahidiService.java

private void showNotification(String tickerText) {

    // This is what should be launched if the user selects our notification.
    Intent baseIntent = new Intent(this, IncidentsTab.class);
    baseIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, baseIntent, 0);

    // choose the ticker text
    newUshahidiReportNotification = new Notification(R.drawable.favicon, tickerText,
            System.currentTimeMillis());
    newUshahidiReportNotification.contentIntent = contentIntent;
    newUshahidiReportNotification.flags = Notification.FLAG_AUTO_CANCEL;
    newUshahidiReportNotification.defaults = Notification.DEFAULT_ALL;
    newUshahidiReportNotification.setLatestEventInfo(this, TAG, tickerText, contentIntent);

    if (UshahidiPref.ringtone) {
        // set the ringer
        Uri ringURI = Uri.fromFile(new File("/system/media/audio/ringtones/ringer.mp3"));
        newUshahidiReportNotification.sound = ringURI;
    }//w w  w  .ja  v a 2  s. c  om

    if (UshahidiPref.vibrate) {
        double vibrateLength = 100 * Math.exp(0.53 * 20);
        long[] vibrate = new long[] { 100, 100, (long) vibrateLength };
        newUshahidiReportNotification.vibrate = vibrate;

        if (UshahidiPref.flashLed) {
            int color = Color.BLUE;
            newUshahidiReportNotification.ledARGB = color;
        }

        newUshahidiReportNotification.ledOffMS = (int) vibrateLength;
        newUshahidiReportNotification.ledOnMS = (int) vibrateLength;
        newUshahidiReportNotification.flags = newUshahidiReportNotification.flags
                | Notification.FLAG_SHOW_LIGHTS;
    }

    mNotificationManager.notify(UshahidiPref.NOTIFICATION_ID, newUshahidiReportNotification);
}

From source file:com.remobile.file.Filesystem.java

public Uri nativeUriForFullPath(String fullPath) {
    Uri ret = null;//from   w w  w .  j a  v  a2  s.com
    if (fullPath != null) {
        String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath();
        if (encodedPath.startsWith("/")) {
            encodedPath = encodedPath.substring(1);
        }
        ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build();
    }
    return ret;
}

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

/**
 * The URI for an asset.//from w  w  w .  ja  v  a  2 s . c  o  m
 * 
 * @param path
 *            The given asset path
 * 
 * @return The URI pointing to the given path
 */
private Uri getUriForAssetPath(String path) {
    String resPath = path.replaceFirst("file:/", "www");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    File dir = activity.getExternalCacheDir();
    if (dir == null) {
        Log.e("Asset", "Missing external cache dir");
        return Uri.EMPTY;
    }
    String storage = dir.toString() + STORAGE_FOLDER;
    File file = new File(storage, fileName);
    new File(storage).mkdir();
    try {
        AssetManager assets = activity.getAssets();
        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = assets.open(resPath);
        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
        return Uri.fromFile(file);
    } catch (Exception e) {
        Log.e("Asset", "File not found: assets/" + resPath);
        e.printStackTrace();
    }
    return Uri.EMPTY;
}

From source file:com.dycody.android.idealnote.async.upgrade.UpgradeProcessor.java

/**
 * Upgrades all the old audio attachments to the new format 3gpp to avoid to exchange them for videos
 *///from   w  ww.j av  a 2  s  . c om
private void onUpgradeTo480() {
    final DbHelper dbHelper = DbHelper.getInstance();
    for (Attachment attachment : dbHelper.getAllAttachments()) {
        if ("audio/3gp".equals(attachment.getMime_type()) || "audio/3gpp".equals(attachment.getMime_type())) {

            // File renaming
            File from = new File(attachment.getUriPath());
            FilenameUtils.getExtension(from.getName());
            File to = new File(from.getParent(), from.getName()
                    .replace(FilenameUtils.getExtension(from.getName()), Constants.MIME_TYPE_AUDIO_EXT));
            from.renameTo(to);

            // Note's attachment update
            attachment.setUri(Uri.fromFile(to));
            attachment.setMime_type(Constants.MIME_TYPE_AUDIO);
            dbHelper.updateAttachment(attachment);
        }
    }
}

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

Uri downloadAndDecrypt(String ticket, String datestr, String objName, File cachefile, String mykey,
        CorralDownloadFuture future, DownloadProgressCallback callback)
        throws IOException, GeneralSecurityException {
    Log.d(TAG, "-----DOWNLOAD+DECRYPT START-----" + (String.valueOf(System.currentTimeMillis())));
    Log.d(TAG, SERVER_URL + objName);
    Log.d(TAG, "Authorization: AWS " + ticket);
    Log.d(TAG, "Date: " + datestr);

    HttpClient http = new DefaultHttpClient();
    HttpGet get = new HttpGet(SERVER_URL + objName);
    get.addHeader("Authorization", "AWS " + ticket);
    get.addHeader("Date", datestr);
    HttpResponse response = http.execute(get);

    DataInputStream is = new DataInputStream(response.getEntity().getContent());
    long contentLength = response.getEntity().getContentLength();

    if (!cachefile.exists()) {
        File tmpFile = new File(cachefile.getAbsoluteFile() + ".tmp");
        tmpFile.getParentFile().mkdirs();
        try {// w w w  .  j  ava2s.com
            CryptUtil cu = new CryptUtil(mykey);
            cu.InitCiphers();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            cu.decrypt(is, fos, contentLength, callback);
            try {
                is.close();
            } catch (IOException e) {
            }
            try {
                fos.close();
            } catch (IOException e) {
            }

            tmpFile.renameTo(cachefile);

        } catch (IOException e) {
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
            throw e;
        } catch (GeneralSecurityException e) {
            throw e;
        }
    }
    return cachefile.exists() ? Uri.fromFile(cachefile) : null;
}

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

/**
 * Called when the video view exits.//from w  w  w .  ja  v a  2s. c o  m
 * 
 * @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").
 * @throws JSONException
 */
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {

    // Result received okay
    if (resultCode == Activity.RESULT_OK) {
        // An audio clip was requested

        final CaptureFG that = this;
        Runnable captureVideo = new Runnable() {

            @Override
            public void run() {

                Uri data = null;

                if (intent != null) {
                    // Get the uri of the video clip
                    data = intent.getData();
                }

                if (data == null) {
                    File movie = new File(getTempDirectoryPath(), "video.3gp");
                    data = Uri.fromFile(movie);
                }

                // create a file object from the uri
                if (data == null) {
                    that.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Error: data is null"));
                } else {
                    results.put(createMediaFile(data));
                    // Send Uri back to JavaScript for viewing video
                    that.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
                }
            }
        };
        this.cordova.getThreadPool().execute(captureVideo);
    }
    // If canceled
    else if (resultCode == Activity.RESULT_CANCELED) {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
        }
        // user canceled the action
        else {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled."));
        }
    }
    // If something else
    else {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
        }
        // something bad happened
        else {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!"));
        }
    }
}

From source file:de.nico.asura.Main.java

private void setList() {
    ListView list = (ListView) findViewById(R.id.listView_main);
    ListAdapter adapter = new SimpleAdapter(this, downloadList, android.R.layout.simple_list_item_1,
            new String[] { TAG_NAME }, new int[] { android.R.id.text1 });
    list.setAdapter(adapter);//from   www  . ja  v a  2s  . c  o m

    // Do nothing when there is no Internet
    if (!(Utils.isNetworkAvailable(this))) {
        return;
    }
    // React when user click on item in the list
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {

            Uri downloadUri = Uri.parse(downloadList.get(pos).get(TAG_URL));
            String title = downloadList.get(pos).get(TAG_NAME);
            file = new File(Environment.getExternalStorageDirectory() + "/" + localLoc + "/"
                    + downloadList.get(pos).get(TAG_FILENAME) + ".pdf");
            Uri dest = Uri.fromFile(file);

            if (file.exists()) {
                Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                pdfIntent.setDataAndType(dest, "application/pdf");
                pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                try {
                    startActivity(pdfIntent);
                } catch (ActivityNotFoundException e) {
                    Utils.makeLongToast(Main.this, noPDF);
                    Log.e("ActivityNotFoundException", e.toString());
                }
                return;
            }

            // Download PDF
            Request request = new Request(downloadUri);
            request.setTitle(title).setDestinationUri(dest);
            downloadID = downloadManager.enqueue(request);
        }

    });

}

From source file:com.codebutler.farebot.fragments.CardsFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    try {//ww w  .  j a  va2s  .  c  o m
        if (item.getItemId() == R.id.import_clipboard) {
            @SuppressWarnings("deprecation")
            ClipboardManager clipboard = (ClipboardManager) getActivity()
                    .getSystemService(Activity.CLIPBOARD_SERVICE);
            onCardsImported(ExportHelper.importCardsXml(getActivity(), clipboard.getText().toString()));
            return true;

        } else if (item.getItemId() == R.id.import_file) {
            Uri uri = Uri.fromFile(Environment.getExternalStorageDirectory());
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.putExtra(Intent.EXTRA_STREAM, uri);
            i.setType("application/xml");
            startActivityForResult(Intent.createChooser(i, "Select File"), REQUEST_SELECT_FILE);
            return true;

        } else if (item.getItemId() == R.id.import_sd) {
            String xml = FileUtils.readFileToString(new File(SD_EXPORT_PATH));
            onCardsImported(ExportHelper.importCardsXml(getActivity(), xml));
            return true;

        } else if (item.getItemId() == R.id.copy_xml) {
            @SuppressWarnings("deprecation")
            ClipboardManager clipboard = (ClipboardManager) getActivity()
                    .getSystemService(Activity.CLIPBOARD_SERVICE);
            clipboard.setText(ExportHelper.exportCardsXml(getActivity()));
            Toast.makeText(getActivity(), "Copied to clipboard.", 5).show();
            return true;

        } else if (item.getItemId() == R.id.share_xml) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, ExportHelper.exportCardsXml(getActivity()));
            startActivity(intent);
            return true;

        } else if (item.getItemId() == R.id.save_xml) {
            String xml = ExportHelper.exportCardsXml(getActivity());
            File file = new File(SD_EXPORT_PATH);
            FileUtils.writeStringToFile(file, xml, "UTF-8");
            Toast.makeText(getActivity(), "Wrote FareBot-Export.xml to USB Storage.", 5).show();
            return true;
        }
    } catch (Exception ex) {
        Utils.showError(getActivity(), ex);
    }
    return false;
}

From source file:com.codebutler.farebot.activities.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    try {//from w  ww .j  a  v  a 2s  .c  o m
        if (item.getItemId() == R.id.supported_cards) {
            startActivity(new Intent(this, SupportedCardsActivity.class));
            return true;

        } else if (item.getItemId() == R.id.about) {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://codebutler.github.com/farebot")));
            return true;

        } else if (item.getItemId() == R.id.import_clipboard) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            onCardsImported(ExportHelper.importCardsXml(this, clipboard.getText().toString()));
            return true;

        } else if (item.getItemId() == R.id.import_file) {
            Uri uri = Uri.fromFile(Environment.getExternalStorageDirectory());
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.putExtra(Intent.EXTRA_STREAM, uri);
            i.setType("application/xml");
            startActivityForResult(Intent.createChooser(i, "Select File"), SELECT_FILE);
            return true;

        } else if (item.getItemId() == R.id.import_sd) {
            String xml = FileUtils.readFileToString(new File(SD_EXPORT_PATH));
            onCardsImported(ExportHelper.importCardsXml(this, xml));
            return true;

        } else if (item.getItemId() == R.id.copy_xml) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            clipboard.setText(ExportHelper.exportCardsXml(this));
            Toast.makeText(this, "Copied to clipboard.", 5).show();
            return true;

        } else if (item.getItemId() == R.id.share_xml) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, ExportHelper.exportCardsXml(this));
            startActivity(intent);
            return true;

        } else if (item.getItemId() == R.id.save_xml) {
            String xml = ExportHelper.exportCardsXml(this);
            File file = new File(SD_EXPORT_PATH);
            FileUtils.writeStringToFile(file, xml, "UTF-8");
            Toast.makeText(this, "Wrote FareBot-Export.xml to USB Storage.", 5).show();
            return true;

        } else if (item.getItemId() == R.id.prefs) {
            startActivity(new Intent(this, FareBotPreferenceActivity.class));
        }
    } catch (Exception ex) {
        Utils.showError(this, ex);
    }
    return false;
}