最近公司做了一個項目需要檢視手機視訊,在android 8的模拟器上正常。在android 5.1的模拟器下卻報了一個錯誤:
Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.PICK dat=content://media/external/video/media
cmp=com.android.music/.VideoBrowserActivity } from ProcessRecord{1b308dad 5422:com.videoclipper.demo/u0a58} (pid=5422, uid=10058) not exported from uid 10036
講道理不應該有權限問題的。因為target為21,而且api22沒有運作時權限,android 8也可以正常運作。這個現象真的很莫名其妙啊。經過搜尋找到了一種解決方法:
原文// contentId will have the video content id as given by Content Resolver
// In this nparticular application, contentId is retrieved from ListActivity with custom adapter
Uri contentUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentId);
try {
Intent intent = new Intent(Intent.ACTION_VIEW, contentUri);
startActivity(intent);
}
catch (ActivityNotFoundException e) {//SecurityException 也可以
Toast.makeText(this, "Not Supported", Toast.LENGTH_SHORT).show();
}
要調用 Gallery browser 使用以下代碼:
someMethod() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setType("video/*");
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == 1) && (resultCode == RESULT_OK) && (data != null)) {
Log.i("---------------------", data.getData().getEncodedPath());
mIntentFromGallery = data;
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setType("video/*");
intent.setData(data.getData());
try
{
startActivity(intent);
}
catch(Exception e)
{
}
} else {
setResult(RESULT_CANCELED);
finish();
}
}
綜合起來的解決方案就是:
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "video/*");
startActivityForResult(intent, REQUEST_CODEE_VIDEO);