private String getMimeTypeFromPath(String path) { String extension = path; int lastDot = extension.lastIndexOf('.'); if (lastDot != -1) { extension = extension.substring(lastDot + 1); } // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185). extension = extension.toLowerCase(Locale.getDefault()); if (extension.equals("3ga")) { return "audio/3gpp"; } else if (extension.equals("js")) { // Missing from the map :(. return "text/javascript"; } return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }
protected void showNotification(String notificationText) { // TODO Auto-generated method stub NotificationCompat.Builder build = new NotificationCompat.Builder( activity); build.setSmallIcon(OneSheeldApplication.getNotificationIcon()); build.setContentTitle(activity.getString(R.string.data_logger_shield_name)); build.setContentText(notificationText); build.setTicker(notificationText); build.setWhen(System.currentTimeMillis()); build.setAutoCancel(true); Toast.makeText(activity, notificationText, Toast.LENGTH_SHORT).show(); Vibrator v = (Vibrator) activity .getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(1000); Intent notificationIntent = new Intent(Intent.ACTION_VIEW); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String mimeFileType = mimeTypeMap.getMimeTypeFromExtension("csv"); if(Build.VERSION.SDK_INT>=24) { Uri fileURI = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", new File(filePath == null || filePath.length() == 0 ? "" : filePath)); notificationIntent.setDataAndType(fileURI, mimeFileType); } else{ notificationIntent.setDataAndType(Uri.fromFile(new File(filePath == null || filePath.length() == 0 ? "" : filePath)), mimeFileType); } notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); notificationIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); PendingIntent intent = PendingIntent.getActivity(activity, 0, notificationIntent, 0); build.setContentIntent(intent); Notification notification = build.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManager notificationManager = (NotificationManager) activity .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify((int) new Date().getTime(), notification); }
/** * To find out the extension of required object in given uri * Solution by http://stackoverflow.com/a/36514823/1171484 */ public static String getMimeType(Activity context, Uri uri) { String extension; //Check uri format to avoid null if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { //If scheme is a content extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri)); if (TextUtils.isEmpty(extension))extension=MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString()); } else { //If scheme is a File //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters. extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString()); if (TextUtils.isEmpty(extension))extension=MimeTypeMap.getSingleton().getExtensionFromMimeType(context.getContentResolver().getType(uri)); } if(TextUtils.isEmpty(extension)){ extension=getMimeTypeByFileName(TUriParse.getFileWithUri(uri,context).getName()); } return extension; }
/** * Callback method to get the result returned by the image picker activity * * @param requestCode a code identifying the request. * @param resultCode a code specifying success or failure of the activity * @param data the returned data, in this case an Intent whose data field * contains the image's content URI. */ public void resultReturned(int requestCode, int resultCode, Intent data) { if (requestCode == this.requestCode && resultCode == Activity.RESULT_OK) { Uri selectedImage = data.getData(); selectionURI = selectedImage.toString(); Log.i(LOG_TAG, "selectionURI = " + selectionURI); // get the file type extension from the intent data Uri ContentResolver cR = container.$context().getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); String extension = "." + mime.getExtensionFromMimeType(cR.getType(selectedImage)); Log.i(LOG_TAG, "extension = " + extension); // save the image to a temp file in external storage, using a name // that includes the extension saveSelectedImageToExternalStorage(extension); AfterPicking(); } }
/** * Method that return openable intent according to the file type * * @param file * @return */ public Intent getOpenableIntent(String file){ if(isExists(currentDir+"/"+file) && new File(currentDir+"/"+file) .isFile()) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(new File(currentDir+"/"+file)); String type=MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap .getFileExtensionFromUrl(uri.toString())); intent.setDataAndType(uri,type); return intent; } else return null; }
public static String getMimeType(String filePath) { if (TextUtils.isEmpty(filePath)) { return ""; } String type = null; String extension = getExtensionName(filePath.toLowerCase()); if (!TextUtils.isEmpty(extension)) { MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extension); } Log.i(TAG, "url:" + filePath + " " + "type:" + type); // FIXME if (StringUtil.isEmpty(type) && filePath.endsWith("aac")) { type = "audio/aac"; } return type; }
private String getMimeTypeForEntry(ZipEntry entry) { if (entry.isDirectory()) { return Document.MIME_TYPE_DIR; } final int lastDot = entry.getName().lastIndexOf('.'); if (lastDot >= 0) { final String extension = entry.getName().substring(lastDot + 1).toLowerCase(Locale.US); final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mimeType != null) { return mimeType; } } return BASIC_MIME_TYPE; }
static String getMimeType(File file) { if (file.isDirectory()) { return null; } String type = "*/*"; final String extension = getExtension(file.getName()); if (extension != null && !extension.isEmpty()) { final String extensionLowerCase = extension.toLowerCase(Locale .getDefault()); final MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extensionLowerCase); if (type == null) { type = MIME_TYPES.get(extensionLowerCase); } } if (type == null) type = "*/*"; return type; }
@Override public DocumentFileCompat createFile(String mimeType, String displayName) { // Tack on extension when valid MIME type provided final String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); if (extension != null) { displayName += "." + extension; } final File target = new File(mFile, displayName); try { target.createNewFile(); return new RawDocumentFile(this, target); } catch (IOException e) { Log.w(TAG, "Failed to createFile: " + e); return null; } }
private void openFile(String filePath) { Uri uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", new File(filePath)); String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString()); String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension (fileExtension); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, mimeType); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, getString(R.string.open_file))); }
/** * Records the content types when user downloads the file by long pressing the * save link context menu option. */ static void recordSaveLinkTypes(String url) { String extension = MimeTypeMap.getFileExtensionFromUrl(url); int mimeType = TYPE_UNKNOWN; if (extension != null) { String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (type != null) { if (type.startsWith("text")) { mimeType = TYPE_TEXT; } else if (type.startsWith("image")) { mimeType = TYPE_IMAGE; } else if (type.startsWith("audio")) { mimeType = TYPE_AUDIO; } else if (type.startsWith("video")) { mimeType = TYPE_VIDEO; } else if (type.equals("application/pdf")) { mimeType = TYPE_PDF; } } } RecordHistogram.recordEnumeratedHistogram( "ContextMenu.SaveLinkType", mimeType, NUM_TYPES); }
/** * If the given MIME type is null, or one of the "generic" types (text/plain * or application/octet-stream) map it to a type that Android can deal with. * If the given type is not generic, return it unchanged. * * We have to implement this ourselves as * MimeTypeMap.remapGenericMimeType() is not public. * See http://crbug.com/407829. * * @param mimeType MIME type provided by the server. * @param url URL of the data being loaded. * @param filename file name obtained from content disposition header * @return The MIME type that should be used for this data. */ static String remapGenericMimeType(String mimeType, String url, String filename) { // If we have one of "generic" MIME types, try to deduce // the right MIME type from the file extension (if any): if (mimeType == null || mimeType.isEmpty() || "text/plain".equals(mimeType) || "application/octet-stream".equals(mimeType) || "binary/octet-stream".equals(mimeType) || "octet/stream".equals(mimeType) || "application/force-download".equals(mimeType) || "application/unknown".equals(mimeType)) { String extension = getFileExtension(url, filename); String newMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (newMimeType != null) { mimeType = newMimeType; } else if (extension.equals("dm")) { mimeType = OMADownloadHandler.OMA_DRM_MESSAGE_MIME; } else if (extension.equals("dd")) { mimeType = OMADownloadHandler.OMA_DOWNLOAD_DESCRIPTOR_MIME; } } return mimeType; }
public final static String getMimeByExt(String ext, String defValue) { if (str(ext)) { String[] descr = getTypeDescrByExt(ext); if (descr != null) return descr[1]; // ask the system MimeTypeMap mime_map = MimeTypeMap.getSingleton(); if (mime_map != null) { String mime = mime_map.getMimeTypeFromExtension(ext.substring(1)); if (str(mime)) return mime; } } return defValue; }
@Test public void testQueryActionViewIntentActivities() throws Exception { File txt = new File("/test.txt"); Uri uri = Uri.fromFile(txt); // 获取扩展名 String extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString()); // 获取MimeType String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); // 创建隐式Intent Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, mimeType); Context context = InstrumentationRegistry.getContext(); PackageManager packageManager = context.getPackageManager(); // 根据Intent查询匹配的Activity列表 List<ResolveInfo> resolvers = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolver : resolvers) { Log.d(TAG, resolver.activityInfo.packageName + "\n" + resolver.activityInfo.name); } }
private static boolean openApk(Context context, File file) { try { Uri uri; if (Build.VERSION.SDK_INT >= 24) { uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file); } else { uri = Uri.fromFile(file); } //create intent open file MimeTypeMap myMime = MimeTypeMap.getSingleton(); Intent intent = new Intent(Intent.ACTION_VIEW); String ext = FileUtils.fileExt(file.getPath()); String mimeType = myMime.getMimeTypeFromExtension(ext != null ? ext : ""); intent.setDataAndType(uri, mimeType); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); context.startActivity(intent); } catch (Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); } return true; }
private void openCameraWithOutput() { String path = new File(Environment.getExternalStorageDirectory(), "ktools").getAbsolutePath(); if (!new File(path).exists()) { new File(path).mkdirs(); } outputImageFile = new File(path, System.currentTimeMillis() + ".png"); if (!outputImageFile.exists()) { try { outputImageFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } //兼容7.0 Uri contentUri = FileProvider.getUriForFile( this, BuildConfig.APPLICATION_ID, outputImageFile ); Log.d(TAG, "openCameraWithOutput: uri = " + contentUri.toString()); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(Intent.EXTRA_MIME_TYPES, MimeTypeMap.getSingleton().getMimeTypeFromExtension("png")); //指定输出路径 intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri); startActivityForResult(intent, REQUEST_CODE_CAPTURE_IMAGE_WITHOUT_COMPRESS); }
/** * Returns the MIME type of a content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * * @param uri A content URI returned by * {@link #getUriForFile(Context, String, File) getUriForFile()}. * @return If the associated file has an extension, the MIME type associated with that * extension; otherwise <code>application/octet-stream</code>. */ @Override public String getType(Uri uri) { // ContentProvider has already checked granted permissions final File file = mStrategy.getFileForUri(uri); final int lastDot = file.getName().lastIndexOf('.'); if (lastDot >= 0) { final String extension = file.getName().substring(lastDot + 1); final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mime != null) { return mime; } } return "application/octet-stream"; }
public static String getMimeTypeForExtension(String path) { String extension = path; int lastDot = extension.lastIndexOf('.'); if (lastDot != -1) { extension = extension.substring(lastDot + 1); } // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185). extension = extension.toLowerCase(Locale.getDefault()); if (extension.equals("3ga")) { return "audio/3gpp"; } return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }
@ScriptInterface public void editFile(String path) { if (path == null) throw new NullPointerException("path == null"); path = "file://" + path; String ext = getExtension(path); String mimeType = TextUtils.isEmpty(ext) ? "*/*" : MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); mContext.startActivity(new Intent(Intent.ACTION_EDIT) .setDataAndType(Uri.parse(path), mimeType) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); }
public void askOpenBackup() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(MimeTypeMap.getSingleton().getMimeTypeFromExtension("zip")); startActivityForResult(intent, BACKUP_FILE_REQUEST_CODE); setSlideAnimation(false); }
public static void openFileInSystem(String path, Context context) { try { MimeTypeMap myMime = MimeTypeMap.getSingleton(); Intent newIntent = new Intent(Intent.ACTION_VIEW); String mimeType = myMime.getMimeTypeFromExtension(fileExt(path).substring(1)); newIntent.setDataAndType(Uri.fromFile(new File(path)), mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(newIntent); } catch (Exception e) { Toast.makeText(context, "No handler for this type of file.", Toast.LENGTH_LONG).show(); } }
public static String getMimeType(String url) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } return type; }
@SuppressLint("SimpleDateFormat") public PlayableItem(Item item, int defaultDuration){ this.item =item; setTitle(item.getTitle()); Res resource = item.getFirstResource(); if (resource != null) { setUri(Uri.parse(resource.getValue())); String mimeType =resource.getProtocolInfo().getContentFormat(); if(mimeType == null || mimeType.equals("")){ String fileExtension = MimeTypeMap.getFileExtensionFromUrl(getUri().toString()); mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension); } setMimeType(mimeType); // calculate duration long millis = defaultDuration; if (resource.getDuration() != null) { try{ String[] tokens = resource.getDuration().split(":"); millis = (Long.valueOf(tokens[0]) * 3600 + Long.valueOf(tokens[1]) * 60 + Long.valueOf(tokens[2])) * 1000; Log.d(getClass().getName(), "resource.getDuration(): " + resource.getDuration() +" millis: " + millis); } catch (Exception e) { Log.d(getClass().getName(), "bad duration format", e); } } setDuration(millis); } }
public static boolean isArchive(@Nullable String name) { if (StringUtils.isBlank(name)) return false; name = name.toLowerCase(); for (String value : ARCHIVE_EXTENSIONS) { String extension = MimeTypeMap.getFileExtensionFromUrl(name); if ((extension != null && value.replace(".", "").equals(extension)) || name.endsWith(value)) return true; } return false; }
/** * Remove file extension from name, but only if exact MIME type mapping * exists. This means we can reapply the extension later. */ private static String removeExtension(String mimeType, String name) { final int lastDot = name.lastIndexOf('.'); if (lastDot >= 0) { final String extension = name.substring(lastDot + 1); final String nameMime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mimeType.equals(nameMime)) { return name.substring(0, lastDot); } } return name; }
public static @Nullable String getCorrectedMimeType(@Nullable String mimeType) { if (mimeType == null) return null; switch(mimeType) { case "image/jpg": return MimeTypeMap.getSingleton().hasMimeType(IMAGE_JPEG) ? IMAGE_JPEG : mimeType; default: return mimeType; } }
public static String getMimeType(String url){ String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extension); } return type; }
private static String getFileName(String mimeType, String displayName) { String extension = MimeTypeMap.getFileExtensionFromUrl(displayName).toLowerCase(); if ((extension == null) || !Objects.equals(mimeType, MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension))) { extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType); if (extension != null) { displayName = displayName + "." + extension; } } return displayName; }
/** * Add file extension to name, but only if exact MIME type mapping exists. */ private static String addExtension(String mimeType, String name) { final String extension = MimeTypeMap.getSingleton() .getExtensionFromMimeType(mimeType); if (extension != null) { return name + "." + extension; } return name; }
/** 使用系统API,根据url获得对应的MIME类型 */ public static String getMimeTypeFromUrl(String url) { String type = null; //使用系统API,获取URL路径中文件的后缀名(扩展名) String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { //使用系统API,获取MimeTypeMap的单例实例,然后调用其内部方法获取文件后缀名(扩展名)所对应的MIME类型 type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } Log.i("bqt", "系统定义的MIME类型为:" + type); return type; }
public static String getTypeForName(String name) { final int lastDot = name.lastIndexOf('.'); if (lastDot >= 0) { final String extension = name.substring(lastDot + 1).toLowerCase(); final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mime != null) { return mime; } } return BASIC_MIME_TYPE; }
static void shareFile(Activity activity, String url) { try { File myFile = new File(url); MimeTypeMap mime = MimeTypeMap.getSingleton(); String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1); String type = mime.getMimeTypeFromExtension(ext); Intent sharingIntent = new Intent("android.intent.action.SEND"); sharingIntent.setType(type); sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile)); activity.startActivity(Intent.createChooser(sharingIntent, activity.getString(R.string.shareWith))); } catch (Exception e) { e.printStackTrace(); } }
@Override public String getType(Uri uri) { String extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString().toLowerCase(Locale.ROOT)); String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (TextUtils.isEmpty(mimeType)) { mimeType = "application/octet-stream"; } return mimeType; }