我正试图打开画廊并选择任何文档(ms,pdf等)或图像。但是在写入ByteArrayOutputStream时会导致内存不足错误。
在Android清单中,largeHeap = true。
Intent intent = new Intent();
String[] mimeTypes = {"image/*",
"application/pdf",
"application/ppt",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/msword",
"text/*"};
intent.setType("*/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Document"), 10);
onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == RESULT_OK) {
if (data != null) {
if (data.getData() != null) {
try {
InputStream iStream = getContentResolver().openInputStream(data.getData());
byte[] inputData = getBytes(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024 * 8;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
请有人可以帮助我做什么?
谢谢。