如何检测android上的多媒体文件属于音频、视频还是图片?要判断扩展名?
如果原生android不支持的媒体文件或者经过修改framework,添加了支持的媒体文件,还要添加扩展名的判断吗?
经过查看android源码发现,framework中有标记为hide的注解,这说明我们的Application layer不能调用这些类以及类下的方法和属性,那么我们只能通过反射机制来调用。那么看一下以下的实现方式。
public class JudgeMultiMediaType {
Class<?> mMediaFile, mMediaFileType;
Method getFileTypeMethod, isAudioFileTypeMethod, isVideoFileTypeMethod, isImageFileTypeMethod;
String methodName = "getBoolean";
String getFileType = "getFileType";
String isAudioFileType = "isAudioFileType";
String isVideoFileType = "isVideoFileType";
String isImageFileType = "isImageFileType";
Field fileType;
public void initReflect() {
try {
mMediaFile = Class.forName("android.media.MediaFile");
mMediaFileType = Class.forName("android.media.MediaFile$MediaFileType");
fileType = mMediaFileType.getField("fileType");
getFileTypeMethod = mMediaFile.getMethod(getFileType, String.class);
isAudioFileTypeMethod = mMediaFile.getMethod(isAudioFileType, int.class);
isVideoFileTypeMethod = mMediaFile.getMethod(isVideoFileType, int.class);
isImageFileTypeMethod = mMediaFile.getMethod(isImageFileType, int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public int getMediaFileType(String path) {
int type = 0;
try {
Object obj = getFileTypeMethod.invoke(mMediaFile, path);
if (obj == null) {
type = -1;
} else {
type = fileType.getInt(obj);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return type;
}
public boolean isAudioFile(int fileType) {
boolean isAudioFile = false;
try {
isAudioFile = (Boolean) isAudioFileTypeMethod.invoke(mMediaFile, fileType);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return isAudioFile;
}
public boolean isVideoFile(int fileType) {
boolean isVideoFile = false;
try {
isVideoFile = (Boolean) isVideoFileTypeMethod.invoke(mMediaFile, fileType);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return isVideoFile;
}
public boolean isImageFile(int fileType) {
boolean isImageFile = false;
try {
isImageFile = (Boolean) isImageFileTypeMethod.invoke(mMediaFile, fileType);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return isImageFile;
}
}
以上代码在android4.1上测试过。