Java Code Examples for android.content.ContentResolver#openFileDescriptor()

The following examples show how to use android.content.ContentResolver#openFileDescriptor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Util.java    From reader with MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Source File: LocalVideoThumbnailProducer.java    From fresco with MIT License 6 votes vote down vote up
@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;
  }
}
 
Example 3
Source File: MainActivity.java    From Pomfshare with GNU General Public License v2.0 6 votes vote down vote up
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));
	}
}
 
Example 4
Source File: Util.java    From droidddle with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 5
Source File: BitmapHelper.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
	 * ファイルからビットマップを読み込んで指定した幅・高さに最も近い大きさの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;
	}
 
Example 6
Source File: MediaStoreHack.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 7
Source File: InstallHistoryActivity.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example 8
Source File: CameraUtil.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 9
Source File: Util.java    From reader with MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 10
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 11
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 12
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 13
Source File: ImageUtil.java    From YiBo with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: BitmapHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * ファイルからビットマップを読み込んで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;
}
 
Example 15
Source File: VideoUtil.java    From VideoProcessor with Apache License 2.0 5 votes vote down vote up
/**
 * 保存文件 存储位置:/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;
}
 
Example 16
Source File: PluginManagerProviderClient.java    From Android-Plugin-Framework with MIT License 5 votes vote down vote up
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;
}
 
Example 17
Source File: Util.java    From reader with MIT License 5 votes vote down vote up
private static ParcelFileDescriptor makeInputStream(
        Uri uri, ContentResolver cr) {
    try {
        return cr.openFileDescriptor(uri, "r");
    } catch (IOException ex) {
        return null;
    }
}
 
Example 18
Source File: Util.java    From reader with MIT License 5 votes vote down vote up
private static ParcelFileDescriptor makeInputStream(
        Uri uri, ContentResolver cr) {
    try {
        return cr.openFileDescriptor(uri, "r");
    } catch (IOException ex) {
        return null;
    }
}
 
Example 19
Source File: Util.java    From droidddle with Apache License 2.0 5 votes vote down vote up
private static ParcelFileDescriptor makeInputStream(Uri uri, ContentResolver cr) {
    try {
        return cr.openFileDescriptor(uri, "r");
    } catch (IOException ex) {
        return null;
    }
}
 
Example 20
Source File: HostMediaPlayerManager.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
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;
    }
}