public class GalleryUtil {
/**
* 系统相册的过滤关键词
*/
private static final String[] SYSTEM_GALLERY_FILTERS = new String[]{"gallery", "photo", "picture"};
/**
* 打开系统图片相册
*/
public static void openSystemImageGallery(Activity activity, int reqCode) {
openSystemGallery(activity, reqCode, "image/*");
}
/**
* 打开系统视频相册
*/
public static void openSystemVideoGallery(Activity activity, int reqCode) {
openSystemGallery(activity, reqCode, "video/*");
}
/**
* 打开系统相册
*
* @param type image/* video/*
*/
public static void openSystemGallery(Activity activity, int reqCode, String type) {
try {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, type);
onlyUseSystemGallery(activity, intent);
activity.startActivityForResult(intent, reqCode);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void onlyUseSystemGallery(Context context, Intent intent) {
if (context == null || intent == null) {
return;
}
try {
//查询系统相册包名
PackageManager packageManager = context.getPackageManager();
if (packageManager == null) {
return;
}
List<ResolveInfo> infos = packageManager.queryIntentActivities(intent, 0);
if (infos == null || infos.size() == 0) {
return;
}
final Set<String> backupPackages = new HashSet<>();
for (ResolveInfo resolveInfo : infos) {
if (resolveInfo == null) {
continue;
}
ApplicationInfo applicationInfo = resolveInfo.activityInfo.applicationInfo;
if (applicationInfo != null && applicationInfo.packageName != null
&& (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
backupPackages.add(applicationInfo.packageName);
}
}
for (String pkg : backupPackages) {
if (backupPackages.size() == 1) {
// 如果包名只有一个,则直接使用
intent.setPackage(pkg);
return;
} else {
// 如果包名有多个,则根据关键字再次筛选一次
for (String filter : SYSTEM_GALLERY_FILTERS) {
if (pkg.contains(filter)) {
intent.setPackage(pkg);
return;
}
}
}
}
} catch (Throwable t) {
}
}
}
网友评论