Java Code Examples for android.content.Intent#normalizeMimeType()

The following examples show how to use android.content.Intent#normalizeMimeType() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: AndroidChromium   File: DownloadUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an Intent to open the file in another app by firing an Intent to Android.
 * @param fileUri  Uri pointing to the file.
 * @param mimeType MIME type for the file.
 * @return Intent that can be used to start an Activity for the file.
 */
public static Intent createViewIntentForDownloadItem(Uri fileUri, String mimeType) {
    Intent fileIntent = new Intent(Intent.ACTION_VIEW);
    String normalizedMimeType = Intent.normalizeMimeType(mimeType);
    if (TextUtils.isEmpty(normalizedMimeType)) {
        fileIntent.setData(fileUri);
    } else {
        fileIntent.setDataAndType(fileUri, normalizedMimeType);
    }
    fileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    fileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return fileIntent;
}
 
Example 2
Source Project: AndroidChromium   File: DownloadUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Opens a file in Chrome or in another app if appropriate.
 * @param file path to the file to open.
 * @param mimeType mime type of the file.
 * @param isOffTheRecord whether we are in an off the record context.
 * @return whether the file could successfully be opened.
 */
public static boolean openFile(File file, String mimeType, boolean isOffTheRecord) {
    Context context = ContextUtils.getApplicationContext();
    Intent viewIntent = createViewIntentForDownloadItem(Uri.fromFile(file), mimeType);
    DownloadManagerService service = DownloadManagerService.getDownloadManagerService(context);

    // Check if Chrome should open the file itself.
    if (service.isDownloadOpenableInBrowser(isOffTheRecord, mimeType)) {
        // Share URIs use the content:// scheme when able, which looks bad when displayed
        // in the URL bar.
        Uri fileUri = Uri.fromFile(file);
        Uri shareUri = getUriForItem(file);
        String normalizedMimeType = Intent.normalizeMimeType(mimeType);

        Intent intent =
                getMediaViewerIntentForDownloadItem(fileUri, shareUri, normalizedMimeType);
        IntentHandler.startActivityForTrustedIntent(intent, context);
        return true;
    }

    // Check if any apps can open the file.
    try {
        context.startActivity(viewIntent);
        return true;
    } catch (ActivityNotFoundException e) {
        // Can't launch the Intent.
        Toast.makeText(context, context.getString(R.string.download_cant_open_file),
                     Toast.LENGTH_SHORT)
                .show();
        return false;
    }
}
 
Example 3
Source Project: 365browser   File: DownloadUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an Intent to open the file in another app by firing an Intent to Android.
 * @param fileUri  Uri pointing to the file.
 * @param mimeType MIME type for the file.
 * @return Intent that can be used to start an Activity for the file.
 */
public static Intent createViewIntentForDownloadItem(Uri fileUri, String mimeType) {
    Intent fileIntent = new Intent(Intent.ACTION_VIEW);
    String normalizedMimeType = Intent.normalizeMimeType(mimeType);
    if (TextUtils.isEmpty(normalizedMimeType)) {
        fileIntent.setData(fileUri);
    } else {
        fileIntent.setDataAndType(fileUri, normalizedMimeType);
    }
    fileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    fileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return fileIntent;
}
 
Example 4
Source Project: 365browser   File: DownloadUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Opens a file in Chrome or in another app if appropriate.
 * @param file path to the file to open.
 * @param mimeType mime type of the file.
 * @param downloadGuid The associated download GUID.
 * @param isOffTheRecord whether we are in an off the record context.
 * @return whether the file could successfully be opened.
 */
public static boolean openFile(
        File file, String mimeType, String downloadGuid, boolean isOffTheRecord) {
    Context context = ContextUtils.getApplicationContext();
    DownloadManagerService service = DownloadManagerService.getDownloadManagerService();

    // Check if Chrome should open the file itself.
    if (service.isDownloadOpenableInBrowser(isOffTheRecord, mimeType)) {
        // Share URIs use the content:// scheme when able, which looks bad when displayed
        // in the URL bar.
        Uri fileUri = Uri.fromFile(file);
        Uri contentUri = getUriForItem(file);
        String normalizedMimeType = Intent.normalizeMimeType(mimeType);

        Intent intent =
                getMediaViewerIntentForDownloadItem(fileUri, contentUri, normalizedMimeType);
        IntentHandler.startActivityForTrustedIntent(intent);
        service.updateLastAccessTime(downloadGuid, isOffTheRecord);
        return true;
    }

    // Check if any apps can open the file.
    try {
        // TODO(qinmin): Move this to an AsyncTask so we don't need to temper with strict mode.
        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
        Uri uri = ApiCompatibilityUtils.getUriForDownloadedFile(file);
        StrictMode.setThreadPolicy(oldPolicy);
        Intent viewIntent = createViewIntentForDownloadItem(uri, mimeType);
        context.startActivity(viewIntent);
        service.updateLastAccessTime(downloadGuid, isOffTheRecord);
        return true;
    } catch (ActivityNotFoundException e) {
        // Can't launch the Intent.
        Toast.makeText(context, context.getString(R.string.download_cant_open_file),
                     Toast.LENGTH_SHORT)
                .show();
        return false;
    }
}
 
Example 5
Source Project: android_9.0.0_r45   File: NdefRecord.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Create a new NDEF Record containing MIME data.<p>
 * Use this method to encode MIME-typed data into an NDEF Record,
 * such as "text/plain", or "image/jpeg".<p>
 * The mimeType parameter will be normalized with
 * {@link Intent#normalizeMimeType} to follow Android best
 * practices for intent filtering, for example to force lower-case.
 * However the unchecked exception
 * {@link IllegalArgumentException} may be thrown
 * if the mimeType parameter has serious problems,
 * for example if it is empty, so always catch this
 * exception if you are passing user-generated data into this method.
 * <p>
 * For efficiency, This method might not make an internal copy of the
 * mimeData byte array, so take care not
 * to modify the mimeData byte array while still using the returned
 * NdefRecord.
 *
 * @param mimeType a valid MIME type
 * @param mimeData MIME data as bytes
 * @return an NDEF Record containing the MIME-typed data
 * @throws IllegalArugmentException if the mimeType is empty or invalid
 *
 */
public static NdefRecord createMime(String mimeType, byte[] mimeData) {
    if (mimeType == null) throw new NullPointerException("mimeType is null");

    // We only do basic MIME type validation: trying to follow the
    // RFCs strictly only ends in tears, since there are lots of MIME
    // types in common use that are not strictly valid as per RFC rules
    mimeType = Intent.normalizeMimeType(mimeType);
    if (mimeType.length() == 0) throw new IllegalArgumentException("mimeType is empty");
    int slashIndex = mimeType.indexOf('/');
    if (slashIndex == 0) throw new IllegalArgumentException("mimeType must have major type");
    if (slashIndex == mimeType.length() - 1) {
        throw new IllegalArgumentException("mimeType must have minor type");
    }
    // missing '/' is allowed

    // MIME RFCs suggest ASCII encoding for content-type
    byte[] typeBytes = mimeType.getBytes(StandardCharsets.US_ASCII);
    return new NdefRecord(TNF_MIME_MEDIA, typeBytes, null, mimeData);
}
 
Example 6
/**
 * Create a new NDEF Record containing MIME data.<p>
 * Use this method to encode MIME-typed data into an NDEF Record,
 * such as "text/plain", or "image/jpeg".<p>
 * The mimeType parameter will be normalized with
 * {@link Intent#normalizeMimeType} to follow Android best
 * practices for intent filtering, for example to force lower-case.
 * However the unchecked exception
 * {@link IllegalArgumentException} may be thrown
 * if the mimeType parameter has serious problems,
 * for example if it is empty, so always catch this
 * exception if you are passing user-generated data into this method.
 * <p>
 * For efficiency, This method might not make an internal copy of the
 * mimeData byte array, so take care not
 * to modify the mimeData byte array while still using the returned
 * NdefRecord.
 *
 * @param mimeType a valid MIME type
 * @param mimeData MIME data as bytes
 * @return an NDEF Record containing the MIME-typed data
 * @throws IllegalArugmentException if the mimeType is empty or invalid
 *
 */
public static NdefRecord createMime(String mimeType, byte[] mimeData) {
    if (mimeType == null) throw new NullPointerException("mimeType is null");

    // We only do basic MIME type validation: trying to follow the
    // RFCs strictly only ends in tears, since there are lots of MIME
    // types in common use that are not strictly valid as per RFC rules
    mimeType = Intent.normalizeMimeType(mimeType);
    if (mimeType.length() == 0) throw new IllegalArgumentException("mimeType is empty");
    int slashIndex = mimeType.indexOf('/');
    if (slashIndex == 0) throw new IllegalArgumentException("mimeType must have major type");
    if (slashIndex == mimeType.length() - 1) {
        throw new IllegalArgumentException("mimeType must have minor type");
    }
    // missing '/' is allowed

    // MIME RFCs suggest ASCII encoding for content-type
    byte[] typeBytes = mimeType.getBytes(Charsets.US_ASCII);
    return new NdefRecord(TNF_MIME_MEDIA, typeBytes, null, mimeData);
}
 
Example 7
Source Project: android_9.0.0_r45   File: NdefRecord.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Map this record to a MIME type, or return null if it cannot be mapped.<p>
 * Currently this method considers all {@link #TNF_MIME_MEDIA} records to
 * be MIME records, as well as some {@link #TNF_WELL_KNOWN} records such as
 * {@link #RTD_TEXT}. If this is a MIME record then the MIME type as string
 * is returned, otherwise null is returned.<p>
 * This method does not perform validation that the MIME type is
 * actually valid. It always attempts to
 * return a string containing the type if this is a MIME record.<p>
 * The returned MIME type will by normalized to lower-case using
 * {@link Intent#normalizeMimeType}.<p>
 * The MIME payload can be obtained using {@link #getPayload}.
 *
 * @return MIME type as a string, or null if this is not a MIME record
 */
public String toMimeType() {
    switch (mTnf) {
        case NdefRecord.TNF_WELL_KNOWN:
            if (Arrays.equals(mType, NdefRecord.RTD_TEXT)) {
                return "text/plain";
            }
            break;
        case NdefRecord.TNF_MIME_MEDIA:
            String mimeType = new String(mType, StandardCharsets.US_ASCII);
            return Intent.normalizeMimeType(mimeType);
    }
    return null;
}
 
Example 8
/**
 * Map this record to a MIME type, or return null if it cannot be mapped.<p>
 * Currently this method considers all {@link #TNF_MIME_MEDIA} records to
 * be MIME records, as well as some {@link #TNF_WELL_KNOWN} records such as
 * {@link #RTD_TEXT}. If this is a MIME record then the MIME type as string
 * is returned, otherwise null is returned.<p>
 * This method does not perform validation that the MIME type is
 * actually valid. It always attempts to
 * return a string containing the type if this is a MIME record.<p>
 * The returned MIME type will by normalized to lower-case using
 * {@link Intent#normalizeMimeType}.<p>
 * The MIME payload can be obtained using {@link #getPayload}.
 *
 * @return MIME type as a string, or null if this is not a MIME record
 */
public String toMimeType() {
    switch (mTnf) {
        case NdefRecord.TNF_WELL_KNOWN:
            if (Arrays.equals(mType, NdefRecord.RTD_TEXT)) {
                return "text/plain";
            }
            break;
        case NdefRecord.TNF_MIME_MEDIA:
            String mimeType = new String(mType, Charsets.US_ASCII);
            return Intent.normalizeMimeType(mimeType);
    }
    return null;
}