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.granita.contacticloudsync.ui.DebugInfoActivity.java

public void onShare(MenuItem item) {
    if (!TextUtils.isEmpty(report)) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Exception Details");

        try {/*  w w  w.  j a  v a2  s. co m*/
            File reportFile = File.createTempFile("debug", ".txt", getExternalCacheDir());
            Constants.log.debug("Writing debug info to " + reportFile.getAbsolutePath());
            FileWriter writer = new FileWriter(reportFile);
            writer.write(report);
            writer.close();

            sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(reportFile));
        } catch (IOException e) {
            // let's hope the report is < 1 MB
            sendIntent.putExtra(Intent.EXTRA_TEXT, report);
        }

        startActivity(sendIntent);
    }
}

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

@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
    if (!"file".equals(inputURL.getScheme())) {
        return null;
    }//from w w  w .  ja  v a  2s  . 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 (f.isDirectory() || inputURL.getPath().endsWith("/")) {
        // Add trailing / for directories.
        b.appendEncodedPath("");
    }
    return LocalFilesystemURL.parse(b.build());
}

From source file:im.delight.android.baselib.Social.java

/**
 * Constructs an Intent for sharing/sending a file and starts Activity chooser for that Intent
 *
 * @param context Context reference to start the Activity chooser from
 * @param windowTitle the string to be used as the window title for the Activity chooser
 * @param file the File instance to be shared
 * @param mimeType the MIME type for the file to be shared (e.g. image/jpeg)
 * @param messageTitle the message title/subject that may be provided in addition to the file, if supported by the target app
 *//*www  .j  a  v a  2  s  . c  om*/
public static void shareFile(Context context, String windowTitle, File file, final String mimeType,
        String messageTitle) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setType(mimeType);
    intent.putExtra(Intent.EXTRA_SUBJECT, messageTitle);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    context.startActivity(Intent.createChooser(intent, windowTitle));
}

From source file:edu.mit.mobile.android.net.DownloadLoader.java

@Override
public Uri loadInBackground() {
    boolean alreadyHasDownload = false;

    if (!outdir.exists() && !outdir.mkdirs()) {
        mException = new IOException("could not mkdirs: " + outdir.getAbsolutePath());
        return null;
    }//from w  ww  .j a va 2  s . co  m
    final String fname = mUrl.substring(mUrl.lastIndexOf('/'));
    final File outfile = new File(outdir, fname);

    alreadyHasDownload = outfile.exists() && outfile.length() > MINIMUM_REASONABLE_VIDEO_SIZE;

    final long lastModified = outfile.exists() ? outfile.lastModified() : 0;

    try {
        final NetworkInfo netInfo = mCm.getActiveNetworkInfo();
        if (netInfo == null || !netInfo.isConnected()) {
            // no connection, but there's already a file. Hopefully it works!
            if (alreadyHasDownload) {
                return Uri.fromFile(outfile);
            } else {
                mException = new IOException(getContext().getString(R.string.err_no_data_connection));
                return null;
            }
        }

        HttpURLConnection hc = (HttpURLConnection) new URL(mUrl).openConnection();

        hc.setInstanceFollowRedirects(true);

        if (lastModified != 0) {
            hc.setIfModifiedSince(lastModified);
        }

        int resp = hc.getResponseCode();

        if (resp >= 300 && resp < 400) {

            final String redirectUrl = hc.getURL().toExternalForm();

            if (BuildConfig.DEBUG) {
                Log.d(TAG, "following redirect to " + redirectUrl);
            }
            hc = (HttpURLConnection) new URL(redirectUrl).openConnection();

            if (lastModified != 0) {
                hc.setIfModifiedSince(lastModified);
            }
            resp = hc.getResponseCode();
        }

        if (resp != HttpStatus.SC_OK && resp != HttpStatus.SC_NOT_MODIFIED) {
            Log.e(TAG, "got a non-200 response from server");
            mException = new NetworkProtocolException("Received " + resp + " response from server");
            return null;
        }
        if (resp == HttpStatus.SC_NOT_MODIFIED) {
            if (Constants.DEBUG) {
                Log.d(TAG, "got NOT MODIFIED");
            }
            // verify the integrity of the file
            if (alreadyHasDownload) {
                if (Constants.DEBUG) {
                    Log.d(TAG, fname + " has not been modified since it was downloaded last");
                }
                return Uri.fromFile(outfile);
            } else {
                // re-request without the if-modified header. This shouldn't happen.
                hc = (HttpURLConnection) new URL(mUrl).openConnection();
                final int responseCode = hc.getResponseCode();
                if (responseCode != HttpStatus.SC_OK) {
                    Log.e(TAG, "got a non-200 response from server");
                    mException = new NetworkProtocolException(
                            "Received " + responseCode + " response from server");
                    return null;
                }
            }
        }

        final int contentLength = hc.getContentLength();

        if (contentLength == 0) {
            Log.e(TAG, "got an empty response from server");
            mException = new IOException("Received an empty response from server.");
            return null;

        } else if (contentLength < MINIMUM_REASONABLE_VIDEO_SIZE) { // this is probably not a
                                                                    // video
            Log.e(TAG, "got a very small response from server of length " + hc.getContentLength());
            mException = new IOException("Received an unusually-small response from server.");
            return null;
        }
        boolean downloadSucceeded = false;
        try {

            final BufferedInputStream bis = new BufferedInputStream(hc.getInputStream());
            final FileOutputStream fos = new FileOutputStream(outfile);
            if (Constants.DEBUG) {
                Log.d(TAG, "downloading...");
            }
            StreamUtils.inputStreamToOutputStream(bis, fos);

            fos.close();

            // store the server's last modified date in the filesystem
            outfile.setLastModified(hc.getLastModified());

            downloadSucceeded = true;
            if (Constants.DEBUG) {
                Log.d(TAG, "done! Saved to " + outfile);
            }
            return Uri.fromFile(outfile);

        } finally {
            hc.disconnect();
            // cleanup if this is the first attempt to download
            if (!alreadyHasDownload && !downloadSucceeded) {
                outfile.delete();
            }
        }
    } catch (final IOException e) {
        Log.e(TAG, "error downloading file", e);
        mException = e;
        return null;
    }
}

From source file:im.delight.android.commons.Social.java

/**
 * Displays an application chooser and shares the specified file using the selected application
 *
 * @param context a context reference/*from   w  ww .  j ava  2  s  . c o m*/
 * @param windowTitle the title for the application chooser's window
 * @param fileToShare the file to be shared
 * @param mimeTypeForFile the MIME type for the file to be shared (e.g. `image/jpeg`)
 * @param subjectTextToShare the message title or subject for the file, if supported by the target application
 */
public static void shareFile(final Context context, final String windowTitle, final File fileToShare,
        final String mimeTypeForFile, final String subjectTextToShare) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setType(mimeTypeForFile);
    intent.putExtra(Intent.EXTRA_SUBJECT, subjectTextToShare);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileToShare));
    context.startActivity(Intent.createChooser(intent, windowTitle));
}

From source file:com.haw3d.jadvalKalemat.versions.GingerbreadUtil.java

@Override
@SuppressWarnings("unused") // Ignore dead code warning
public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification,
        String title, HttpContext httpContext) throws IOException {
    // The DownloadManager can sometimes be buggy and can cause spurious
    // errors, see
    // http://code.google.com/p/android/issues/detail?id=18462
    // Since puzzle files are very small (a few KB), we don't need to use
    // any of the useful features the DownloadManager provides, such as
    // resuming interrupted downloads and resuming downloads across
    // system reboots.  So for now, just use the ordinary
    // DefaultHttpClient.
    ////from   ww  w . j  av a 2s.  c  om
    // Also, pre-ICS download managers don't support HTTPS.
    if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) {
        super.downloadFile(url, headers, destination, notification, title, httpContext);
        return;
    }

    DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

    Request request = new Request(Uri.parse(url.toString()));
    File tempFile = new File(jadvalKalematApplication.TEMP_DIR, destination.getName());

    request.setDestinationUri(Uri.fromFile(tempFile));

    for (Entry<String, String> entry : headers.entrySet()) {
        request.addRequestHeader(entry.getKey(), entry.getValue());
    }

    request.setMimeType("application/x-crossword");

    setNotificationVisibility(request, notification);

    request.setTitle(title);
    long id = mgr.enqueue(request);
    Long idObj = id;

    String scrubbedUrl = AbstractDownloader.scrubUrl(url);
    LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")");

    // If the request completed really fast, we're done
    DownloadingFile downloadingFile;
    boolean completed = false;
    boolean succeeded = false;
    int status = -1;
    synchronized (completedDownloads) {
        downloadingFile = completedDownloads.remove(idObj);
        if (downloadingFile != null) {
            completed = true;
            succeeded = downloadingFile.succeeded;
            status = downloadingFile.status;
        } else {
            downloadingFile = new DownloadingFile();
            waitingDownloads.put(idObj, downloadingFile);
        }
    }

    // Wait for the request to complete, if it hasn't completed already
    if (!completed) {
        try {
            synchronized (downloadingFile) {
                if (!downloadingFile.completed) {
                    downloadingFile.wait();
                }
                succeeded = downloadingFile.succeeded;
                status = downloadingFile.status;
            }
        } catch (InterruptedException e) {
            LOG.warning("Download interrupted: " + scrubbedUrl);
            throw new IOException("Download interrupted");
        }
    }

    LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl);

    if (succeeded) {
        if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) {
            LOG.warning("Failed to rename " + tempFile + " to " + destination);
            throw new IOException("Failed to rename " + tempFile + " to " + destination);
        }
    } else {
        throw new HTTPException(status);
    }
}

From source file:com.adamrosenfield.wordswithcrosses.versions.GingerbreadUtil.java

@Override
@SuppressWarnings("unused") // Ignore dead code warning
public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification,
        String title, HttpContext httpContext) throws IOException {
    // The DownloadManager can sometimes be buggy and can cause spurious
    // errors, see
    // http://code.google.com/p/android/issues/detail?id=18462
    // Since puzzle files are very small (a few KB), we don't need to use
    // any of the useful features the DownloadManager provides, such as
    // resuming interrupted downloads and resuming downloads across
    // system reboots.  So for now, just use the ordinary
    // DefaultHttpClient.
    ///*from   w w w  . j a  v  a 2 s .c  o m*/
    // Also, pre-ICS download managers don't support HTTPS.
    if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) {
        super.downloadFile(url, headers, destination, notification, title, httpContext);
        return;
    }

    DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

    Request request = new Request(Uri.parse(url.toString()));
    File tempFile = new File(WordsWithCrossesApplication.TEMP_DIR, destination.getName());

    request.setDestinationUri(Uri.fromFile(tempFile));

    for (Entry<String, String> entry : headers.entrySet()) {
        request.addRequestHeader(entry.getKey(), entry.getValue());
    }

    request.setMimeType("application/x-crossword");

    setNotificationVisibility(request, notification);

    request.setTitle(title);
    long id = mgr.enqueue(request);
    Long idObj = id;

    String scrubbedUrl = AbstractDownloader.scrubUrl(url);
    LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")");

    // If the request completed really fast, we're done
    DownloadingFile downloadingFile;
    boolean completed = false;
    boolean succeeded = false;
    int status = -1;
    synchronized (completedDownloads) {
        downloadingFile = completedDownloads.remove(idObj);
        if (downloadingFile != null) {
            completed = true;
            succeeded = downloadingFile.succeeded;
            status = downloadingFile.status;
        } else {
            downloadingFile = new DownloadingFile();
            waitingDownloads.put(idObj, downloadingFile);
        }
    }

    // Wait for the request to complete, if it hasn't completed already
    if (!completed) {
        try {
            synchronized (downloadingFile) {
                if (!downloadingFile.completed) {
                    downloadingFile.wait();
                }
                succeeded = downloadingFile.succeeded;
                status = downloadingFile.status;
            }
        } catch (InterruptedException e) {
            LOG.warning("Download interrupted: " + scrubbedUrl);
            throw new IOException("Download interrupted");
        }
    }

    LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl);

    if (succeeded) {
        if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) {
            LOG.warning("Failed to rename " + tempFile + " to " + destination);
            throw new IOException("Failed to rename " + tempFile + " to " + destination);
        }
    } else {
        throw new HTTPException(status);
    }
}

From source file:com.ideateam.plugin.Emailer.java

private void SendEmail(String email, String subject, String text, String attachFile) {

    String attachPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/UAR2015/" + attachFile;
    File file = new File(attachPath);

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(text));

    this.cordova.getActivity().startActivity(Intent.createChooser(intent, "Send email..."));

}

From source file:me.xingrz.finder.EntriesActivity.java

public void safelyStartViewActivity(File file) {
    safelyStartViewActivity(Uri.fromFile(file), mimeOfFile(file));
}