打开目录
// 获取本地音频
public static void openAudioManager(Context context) {
PermissionUtils.WriteStoragePermissionRequest(context);
Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT); //系统调用Action属性
mIntent.setType("audio/*"); //设置文件类型 mIntent.setType("*/*");
mIntent.addCategory(Intent.CATEGORY_OPENABLE); // 用来指示一个ACTION_GET_CONTENT 的intent
ProjectApplication.activity.startActivityForResult(mIntent, Config.LOCAL_AUDIO_FOR_REQUEST_CODE);
}
// 获取本地视频
public static void openVideoManager(Context context){
PermissionUtils.WriteStoragePermissionRequest(context);
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
ProjectApplication.activity.startActivityForResult(intent,Config.LOCAL_VIDEO_FOR_REQUEST_CODE);
}
// 获取本地联系人
public static void openConnectManager(Context context){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
ProjectApplication.activity.startActivityForResult(intent, PICK_CONTACT);
}
// 调用图库,获取所有本地图片
public static void openImgManager(Context context){
Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);
imageIntent.setType("image/*");
ProjectApplication.activity.startActivityForResult(imageIntent, PICK_IMAGE);
}
获取权限
PermissionUtils获取权限
public static final int PERMISSION_REQUEST_CODE = 0x00123;
public static boolean WriteStoragePermissionRequest(Context context) {
String permissions[] = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
ArrayList<String> toApplyList = PermissionRequest(context, permissions);
return toApplyList.size() != 0;
}
private static ArrayList<String> PermissionRequest(Context context, String[] permissions) {
ArrayList<String> toApplyList = new ArrayList<>();
for (String perm : permissions) {
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, perm)) {
toApplyList.add(perm);
// 进入到这里代表没有权限.
Log.d(TAG, " -=- initPermission: 没有权限,添加到集合并申请:" + perm);
}
}
String tmpList[] = toApplyList.toArray(new String[toApplyList.size()]);
if (!toApplyList.isEmpty()) {
ActivityCompat.requestPermissions(ProjectApplication.activity, tmpList, PERMISSION_REQUEST_CODE);
}
return toApplyList;
}
回传文件
新建回调工具类
负责回传拿到的信息,并在不同界面进行UI更新
public interface VideoCallBack {
void getVideo(boolean isSuccess, String path);
}
public class VideoCallBackUtil {
public static VideoCallBack videoCallBack;
public static VideoRecordCallBack videoRecordCallBack;
public static void setVideoCallBack(VideoCallBack callBack) {
videoCallBack = callBack;
}
public static void setVideoRecordCallBack(VideoRecordCallBack callBack) {
videoRecordCallBack = callBack;
}
}
回传本地数据
在MainActivity中拿到回传本地数据(音视频、图片等)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, " -=-=- onActivityResult()" +
" requestCode:" + requestCode +
" resultCode:" + resultCode +
" data:" + data);
switch (requestCode) {
case Config.LOCAL_AUDIO_FOR_REQUEST_CODE: // 本地音频数据,Activity回调
if (resultCode == RESULT_OK) {
AudioCallBackUtil.audioCallBack.getAudio(true, FilePathUtils.getFilePath(this, data.getData()));
} else {
AudioCallBackUtil.audioCallBack.getAudio(false, null);
}
break;
case Config.LOCAL_VIDEO_FOR_REQUEST_CODE: // 本地视频数据,Activity回调
if (resultCode == RESULT_OK) {
VideoCallBackUtil.videoCallBack.getVideo(true, FilePathUtils.getFilePath(this, data.getData()));
} else {
VideoCallBackUtil.videoCallBack.getVideo(false, null);
}
break;
case Config.VIDEO_RECORD_FOR_REQUEST_CODE: // 录制视频,Activity回调
if (resultCode == RESULT_OK) {
VideoCallBackUtil.videoRecordCallBack.getRecordVideo(true, FilePathUtils.getFilePath(this, data.getData()));
} else {
VideoCallBackUtil.videoRecordCallBack.getRecordVideo(false, null);
}
break;
}
}
回传数据UI更新
在界面将回传的数据做UI更新
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cb_scene_rescue_local_video:
readLocalVideoFile();
changeRescueContentCheckBox();
break;
case R.id.cb_scene_rescue_local_audio:
readLocalAudioFile();
changeRescueContentCheckBox();
break;
...
}
}
private void readLocalAudioFile(){
Utils.openAudioManager(getContext());
AudioCallBackUtil.setAudioCallBack((isSuccess, path) -> {
Log.d(TAG, "onClick local audio, path: " + path);
if (isSuccess) {
isLocalAudio = true;
rescueContentAdapter.addFileItem(new MultipleFileEntity(Config.LOCAL_AUDIO_RESOURCE, new File(path)));
changeRescueContentCheckBox();
rvRescueInformList.setVisibility(View.VISIBLE);
Log.d(TAG, "setAudioCallBack() isSuccess:" + isSuccess + " path:" + path);
} else {
Log.d(TAG, "onClick local audio failure");
}
changeRescueContentCheckBox();
});
}
private void readLocalVideoFile(){
Utils.openVideoManager(getContext());
VideoCallBackUtil.setVideoCallBack(((isSuccess, path) -> {
Log.d(TAG, "onClick local video, path:" + path);
if (isSuccess) {
isLocalVideo = true;
rescueContentAdapter.addFileItem(new MultipleFileEntity(Config.LOCAL_VIDEO_RESOURCE, new File(path)));
changeRescueContentCheckBox();
rvRescueInformList.setVisibility(View.VISIBLE);
Log.d(TAG, "setVideoCallBack() isSuccess:" + isSuccess + " path:" + path);
} else {
Log.d(TAG, "onClick local video failure");
}
changeRescueContentCheckBox();
}));
}
private void changeRescueContentCheckBox() {
cbSceneRescueText.setChecked(isText && rescueContentAdapter.containTxtFile());
cbSceneRescueAudio.setChecked(isAudio && rescueContentAdapter.containAudioFile());
cbSceneRescueLocalAudio.setChecked(isLocalAudio && rescueContentAdapter.containsLocalAudioFile());
cbSceneRescueLocalVideo.setChecked(isLocalVideo && rescueContentAdapter.containsLocalVideoFile());
cbSceneRescueVideo.setChecked(isVideo && rescueContentAdapter.containsVideoFile());
}
获取文件路径
因为onActivityResult返回data返回的是一串url,所以需要获取文件路径,才能拿到本地文件。
public static String getFilePath(Context context,Uri uri) {
if ("file".equalsIgnoreCase(uri.getScheme())) { // 使用第三方应用打开
return uri.getPath();
} else if (uri.getPath().contains("document") && uri.getPath().contains("/storage/emulated/0/")) {
return uri.getPath().split(":")[1];
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { // 4.4以后
return getPath(context, uri);
} else { // 4.4以下下系统调用方法
return getRealPathFromURI(context, uri);
}
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
// TODO 报错
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
参考文章
Intent.ACTION_PICK和Intent.ACTION_GET_CONTENT 调用系统联系人;图片;音乐;视频;