选择文件的时候,如果使用的是第三方软件,一般是直接返回绝对路径的Uri,如果是系统的,则会返回媒体库的xxxx,所以单纯一种方式选择文件,很可能拿到的绝对路径是错的或者是空的,所以需要做几种处理,这里参考博客:https://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html

下面是我弄好的一个选择文件的Activity,为了方便,使用了静态变量设置回调接口,所以直接调用startActivity方法,即可启动选择文件流程,并在回调接口中返回选中的文件的绝对路径,非常方便。

import android.annotation.SuppressLint;

import android.app.Activity;

import android.content.ContentResolver;

import android.content.ContentUris;

import android.content.Context;

import android.content.Intent;

import android.database.Cursor;

import android.net.Uri;

import android.os.Build;

import android.os.Environment;

import android.provider.DocumentsContract;

import android.provider.MediaStore;

import android.text.TextUtils;

import android.widget.Toast;

import com.imxiaoyu.common.base.ui.BaseActivity;

import com.imxiaoyu.common.impl.OnStringListener;

import com.imxiaoyu.common.utils.ALog;

import com.imxiaoyu.common.utils.ToastUtils;

import java.io.File;

import com.example.mp3editor.R;

import com.example.mp3editor.common.impl.OnMusicListener;

import com.example.mp3editor.common.util.MusicUtil;

import com.example.mp3editor.module.index.entity.MusicEntity;

/**

* 选择音乐文件

* Created by Admin on 2017/11/18.

*/

public class SelectFileActivity extends BaseActivity {undefined

/**

* 常量

*/

public final static int FILE_SELECT_CODE = 0x100;

public final static String ACTIVITY_TYPE = “ACTIVITY_TYPE”;

/**

* 变量

*/

private int type = 0;//0-音乐 1-视频

/**

* 接口

*/

private static OnStringListener onStringListener;

@Override

protected int getLayoutId() {undefined

return R.layout.activity_select_file;

}

public static void startActivity(Activity activity, OnMusicListener listener) {undefined

activity.startActivity(new Intent(activity, SelectFileActivity.class));

}

public static void startActivity(Activity activity, int type, OnStringListener listener) {undefined

onStringListener = listener;

Intent intent = new Intent(activity, SelectFileActivity.class);

intent.putExtra(ACTIVITY_TYPE, type);

activity.startActivity(intent);

}

@Override

protected void initData() {undefined

type = getIntent().getIntExtra(ACTIVITY_TYPE, 0);

}

@Override

protected void initView() {undefined

}

@Override

protected void onCreateActivity() {undefined

selectFile();

}

public void finish() {undefined

onStringListener = null;

super.finish();

}

/**

* 调用文件选择软件来选择文件

**/

public void selectFile() {undefined

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

if (type == 0) {undefined

intent.setType(“audio/*”);

} else {undefined

intent.setType(“video/*”);

}

intent.addCategory(Intent.CATEGORY_OPENABLE);

try {undefined

startActivityForResult(Intent.createChooser(intent, getString(R.string.please_select_a_file)), FILE_SELECT_CODE

);

} catch (android.content.ActivityNotFoundException ex) {undefined

// Potentially direct the user to the Market with a Dialog

Toast.makeText(getActivity(), getString(R.string.please_install_the_file_manager), Toast.LENGTH_SHORT)

.show();

}

}

/**

* 根据返回选择的文件,来进行上传操作

**/

@Override

public void onActivityResult(int requestCode, int resultCode, Intent data) {undefined

if (resultCode == Activity.RESULT_OK) {undefined

String path;

Uri uri = data.getData();

if (“file”.equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开

path = uri.getPath();

callback(path);

return;

}

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后

path = getPath(this, uri);

callback(path);

} else {//4.4以下下系统调用方法

path = getRealPathFromURI(uri);

callback(path);

}

}

super.onActivityResult(requestCode, resultCode, data);

}

private void callback(String path) {undefined

if (onStringListener != null) {undefined

onStringListener.onClick(path);

}

finish();

}

public String getRealPathFromURI(Uri contentUri) {undefined

String res = null;

String[] proj = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);

if(null!=cursor&&cursor.moveToFirst()){;

int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

res = cursor.getString(column_index);

cursor.close();

}

return res;

}

/**

* 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使

*/

@SuppressLint(“NewApi”)

public String getPath(final Context context, final Uri uri) {undefined

final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

// DocumentProvider

if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {undefined

// ExternalStorageProvider

if (isExternalStorageDocument(uri)) {undefined

final String docId = DocumentsContract.getDocumentId(uri);

final String[] split = docId.split(“:”);

final String type = split[0];

if (“primary”.equalsIgnoreCase(type)) {undefined

return Environment.getExternalStorageDirectory() + “/” + split[1];

}

}

// DownloadsProvider

else if (isDownloadsDocument(uri)) {undefined

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)) {undefined

final String docId = DocumentsContract.getDocumentId(uri);

final String[] split = docId.split(“:”);

final String type = split[0];

Uri contentUri = null;

if (“image”.equals(type)) {undefined

contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

} else if (“video”.equals(type)) {undefined

contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

} else if (“audio”.equals(type)) {undefined

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())) {undefined

return getDataColumn(context, uri, null, null);

}

// File

else if (“file”.equalsIgnoreCase(uri.getScheme())) {undefined

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 String getDataColumn(Context context, Uri uri, String selection,

String[] selectionArgs) {undefined

Cursor cursor = null;

final String column = “_data”;

final String[] projection = {column};

try {undefined

cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,

null);

if (cursor != null && cursor.moveToFirst()) {undefined

final int column_index = cursor.getColumnIndexOrThrow(column);

return cursor.getString(column_index);

}

} finally {undefined

if (cursor != null)

cursor.close();

}

return null;

}

/**

* @param uri The Uri to check.

* @return Whether the Uri authority is ExternalStorageProvider.

*/

public boolean isExternalStorageDocument(Uri uri) {undefined

return “com.android.externalstorage.documents”.equals(uri.getAuthority());

}

/**

* @param uri The Uri to check.

* @return Whether the Uri authority is MediaProvider.

*/

public boolean isMediaDocument(Uri uri) {undefined

return “com.android.providers.media.documents”.equals(uri.getAuthority());

}

/**

* @param uri The Uri to check.

* @return Whether the Uri authority is DownloadsProvider.

*/

public boolean isDownloadsDocument(Uri uri) {undefined

return “com.android.providers.downloads.documents”.equals(uri.getAuthority());

}

}