Android 打开文件管理器,并返回选中文件的path

1:

点击触发事件:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);

try {
    startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), REQUEST_CODE_GET_IMAGE);
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(ResourceActivity.this, "Please install a File Manager.",  Toast.LENGTH_SHORT).show();
}

2:

处理返回结果

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode != RESULT_OK){
        return;
    }
    switch (requestCode){
        case REQUEST_CODE_GET_IMAGE :
            if (resultCode == RESULT_OK) {
                    Uri selectedMediaUri = data.getData();
                    String path = FileUtils.getPath(ResourceActivity.this, selectedMediaUri);
            }
            break;
        default:
            break;
    }
}

/**
 * 获取文件选择器选中的文件路径
 * @param context
 * @param uri
 * @return
 */
public static String getPath(Context context, Uri uri) {

    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection,null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }

    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}


你可能感兴趣的:(Android 打开文件管理器,并返回选中文件的path)