工作需要,要使用系统的录音机
方法1
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivityForResult(intent, 33);
该方法,停止录音后,会跳转到录音列表页面。需求是点击停止录音的按钮,直接返回调用页面,并带回Uri
方法2
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "audio/*");
intent.setPackage("com.lenovo.soundrecorder");
try {
startActivityForResult(intent, 23);
} catch (Exception e) {
CustomToast.showGrayToast(getContext(),"跳转失败");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FileLogger.getInstance().info("onActivityResult ", "requestCode :"
+ requestCode + " DATA:" + getAudioPath(context,data.getData()));
}
该方式跳转到录音器,能满足需求
另外附录一下 URI转换成绝对地址 的方法
1、适用于URI为如下样式的情况
uri:content://media/external/audio/media/1564
public String getAudioPath(Context context, Uri uri) {
String res = null;
String[] proj =
{MediaStore.Audio.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
2、如果URI是类似于uri:content://com.android.providers.media.documents/document/audio%3A1546
这样的,上边的方法就不能正确获得绝对地址了。可以用如下方法。
public String getDocMediaPath(Uri 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);
}
private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
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;
}
参考文档 Android通过URI获取文件路径