下面列出了android.content.ContentResolver#openFileDescriptor ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static boolean mkdir(final Context context, final File file) throws IOException {
if (file.exists()) {
return file.isDirectory();
}
final File tmpFile = new File(file, ".MediaWriteTemp");
final int albumId = getTemporaryAlbumId(context);
if (albumId == 0) {
throw new IOException("Failed to create temporary album id.");
}
final Uri albumUri = Uri.parse(String.format(Locale.US, ALBUM_ART_URI + "/%d", albumId));
final ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, tmpFile.getAbsolutePath());
final ContentResolver contentResolver = context.getContentResolver();
if (contentResolver.update(albumUri, values, null, null) == 0) {
values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId);
contentResolver.insert(Uri.parse(ALBUM_ART_URI), values);
}
try {
final ParcelFileDescriptor fd = contentResolver.openFileDescriptor(albumUri, "r");
fd.close();
} finally {
delete(context, tmpFile);
}
return file.exists();
}
/**
* Make a bitmap from a given Uri.
*
* @param uri
*/
public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
Uri uri, ContentResolver cr, boolean useNative) {
ParcelFileDescriptor input = null;
try {
input = cr.openFileDescriptor(uri, "r");
BitmapFactory.Options options = null;
if (useNative) {
options = createNativeAllocOptions();
}
return makeBitmap(minSideLength, maxNumOfPixels, uri, cr, input,
options);
} catch (IOException ex) {
return null;
} finally {
closeSilently(input);
}
}
public static boolean isUriValid(Uri uri, ContentResolver resolver)
{
if (uri == null)
{
return false;
}
try
{
ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
if (pfd == null)
{
Log.e(TAG, "Fail to open URI. URI=" + uri);
return false;
}
pfd.close();
} catch (IOException ex)
{
return false;
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_install_history);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.install_history));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String text = "";
try {
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(InstallHistoryService.LOG_URI, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
cursor.close();
}
ParcelFileDescriptor pfd = resolver.openFileDescriptor(InstallHistoryService.LOG_URI, "r");
FileDescriptor fd = pfd.getFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(fd);
text = IOUtils.toString(fileInputStream, Charset.defaultCharset());
} catch (IOException | SecurityException | IllegalStateException e) {
e.printStackTrace();
}
TextView textView = findViewById(R.id.text);
textView.setText(text);
}
/**
* Make a bitmap from a given Uri.
*
* @param uri
*/
public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
Uri uri, ContentResolver cr, boolean useNative) {
ParcelFileDescriptor input = null;
try {
input = cr.openFileDescriptor(uri, "r");
BitmapFactory.Options options = null;
if (useNative) {
options = createNativeAllocOptions();
}
return makeBitmap(minSideLength, maxNumOfPixels, uri, cr, input,
options);
} catch (IOException ex) {
return null;
} finally {
closeSilently(input);
}
}
/**
* ファイルからビットマップを読み込んで指定した幅・高さに最も近い大きさのBitmapとして返す
* @param cr
* @param requestWidth
* @param requestHeight
* @return
* @throws FileNotFoundException
*/
@Nullable
public static Bitmap asBitmap(@NonNull final ContentResolver cr,
final Uri uri,
final int requestWidth, final int requestHeight) throws IOException {
Bitmap bitmap = null;
if (uri != null) {
final ParcelFileDescriptor pfd = cr.openFileDescriptor(uri, "r");
if (pfd != null) {
bitmap = asBitmap(pfd.getFileDescriptor(), requestWidth, requestHeight);
}
}
// if (DEBUG) Log.v(TAG, "asBitmap:" + bitmap);
return bitmap;
}
/**
* Make a bitmap from a given Uri.
*
* @param uri
*/
public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels, Uri uri, ContentResolver cr, boolean useNative) {
ParcelFileDescriptor input = null;
try {
input = cr.openFileDescriptor(uri, "r");
BitmapFactory.Options options = null;
if (useNative) {
options = createNativeAllocOptions();
}
return makeBitmap(minSideLength, maxNumOfPixels, uri, cr, input, options);
} catch (IOException ex) {
return null;
} finally {
closeSilently(input);
}
}
private void displayAndUpload(Host host) {
ContentResolver cr = getContentResolver();
if (imageUri != null) {
ImageView view = (ImageView)findViewById(R.id.sharedImageView);
view.setImageURI(imageUri);
ParcelFileDescriptor inputPFD = null;
try {
inputPFD = cr.openFileDescriptor(imageUri, "r");
} catch (FileNotFoundException e) {
Log.e(tag, e.getMessage());
Toast toast = Toast.makeText(getApplicationContext(), "Unable to read file.", Toast.LENGTH_SHORT);
toast.show();
}
new Uploader(this, inputPFD, host).execute(imageUri.getLastPathSegment(), cr.getType(imageUri));
}
}
@Nullable
private static Bitmap createThumbnailFromContentProvider(
ContentResolver contentResolver, Uri uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
try {
ParcelFileDescriptor videoFile = contentResolver.openFileDescriptor(uri, "r");
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(videoFile.getFileDescriptor());
return mediaMetadataRetriever.getFrameAtTime(-1);
} catch (FileNotFoundException e) {
return null;
}
} else {
return null;
}
}
private static ParcelFileDescriptor makeInputStream(
Uri uri, ContentResolver cr) {
try {
return cr.openFileDescriptor(uri, "r");
} catch (IOException ex) {
return null;
}
}
/**
* 保存文件 存储位置:/storage/emulated/0/DICM/path1/path2/new_photo_file.png
* String path = savaVideoToMediaStore("videp.mp4", "new video file descrition", "video/mp4");
*/
public static String savaVideoToMediaStore(Context context,String videoPath,String name, String description, String mime) {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DISPLAY_NAME, name);
values.put(MediaStore.Video.Media.MIME_TYPE, mime);
values.put(MediaStore.Video.Media.DESCRIPTION, description);
if (Build.VERSION.SDK_INT >= 29) {
values.put(MediaStore.Video.Media.RELATIVE_PATH,"Movies/VideoProcessor");
}
Uri url = null;
String stringUri = null;
ContentResolver cr = context.getContentResolver();
try {
url = cr.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
if (url == null) {
return null;
}
byte[] buffer = new byte[1024];
ParcelFileDescriptor descriptor = cr.openFileDescriptor(url, "w");
FileOutputStream outputStream = new FileOutputStream(descriptor.getFileDescriptor());
InputStream inputStream = new FileInputStream(videoPath);
while (true) {
int readSize = inputStream.read(buffer);
if (readSize == -1) {
break;
}
outputStream.write(buffer, 0, readSize);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
if (url != null) {
cr.delete(url, null, null);
}
}
if (url != null) {
stringUri = url.toString();
}
return stringUri;
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
final long id = Long.parseLong(docId);
final ContentResolver resolver = getContext().getContentResolver();
return resolver.openFileDescriptor(mDm.getUriForDownloadedFile(id), mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
final long id = Long.parseLong(docId);
final ContentResolver resolver = getContext().getContentResolver();
return resolver.openFileDescriptor(mDm.getUriForDownloadedFile(id), mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
final long id = Long.parseLong(docId);
final ContentResolver resolver = getContext().getContentResolver();
return resolver.openFileDescriptor(mDm.getUriForDownloadedFile(id), mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
public static Bitmap scaleImageUriTo(ContentResolver resolver, Uri uri, int size) {
if (resolver == null
|| uri == null
|| size <= 0) {
return null;
}
ParcelFileDescriptor pfd;
try {
pfd = resolver.openFileDescriptor(uri, "r");
} catch (IOException e) {
Logger.debug(e.getMessage(), e);
return null;
}
java.io.FileDescriptor fd = pfd.getFileDescriptor();
BitmapFactory.Options options = new BitmapFactory.Options();
//先指定原始大小
options.inSampleSize = 1;
//只进行大小判断
options.inJustDecodeBounds = true;
//调用此方法得到options得到图片的大小
BitmapFactory.decodeFileDescriptor(fd, null, options);
//获得缩放比例
options.inSampleSize = getScaleSampleSize(options, size);
//OK,我们得到了缩放的比例,现在开始正式读入BitMap数据
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
//根据options参数,减少所需要的内存
Bitmap sourceBitmap = null;
sourceBitmap = BitmapFactory.decodeFileDescriptor(fd, null, options);
return sourceBitmap;
}
/**
* ファイルからビットマップを読み込んでBitmapとして返す
* @param cr
* @return
* @throws FileNotFoundException
*/
@Nullable
public static Bitmap asBitmap(@NonNull final ContentResolver cr, final Uri uri)
throws IOException {
Bitmap bitmap= null;
if (uri != null) {
final ParcelFileDescriptor pfd = cr.openFileDescriptor(uri, "r");
if (pfd != null) {
bitmap = asBitmap(pfd.getFileDescriptor());
}
}
return bitmap;
}
public static ParcelFileDescriptor openFile(Uri uri, String mode) {
Uri newUri = buildNewUri(uri);
ContentResolver resolver = FairyGlobal.getHostApplication().getContentResolver();
try {
LogUtil.d("openFile", uri, newUri);
return resolver.openFileDescriptor(newUri, mode);
} catch (Exception e) {
LogUtil.printException("openFile " + uri, e);
}
return null;
}
private static ParcelFileDescriptor makeInputStream(
Uri uri, ContentResolver cr) {
try {
return cr.openFileDescriptor(uri, "r");
} catch (IOException ex) {
return null;
}
}
private static ParcelFileDescriptor makeInputStream(Uri uri, ContentResolver cr) {
try {
return cr.openFileDescriptor(uri, "r");
} catch (IOException ex) {
return null;
}
}
private FileDescriptor getDescriptorFromUri(final Uri uri) {
ContentResolver resolver = getContentResolver();
try {
ParcelFileDescriptor descriptor = resolver.openFileDescriptor(uri, "r");
if (descriptor == null) {
return null;
}
return descriptor.getFileDescriptor();
} catch (IOException e) {
return null;
}
}