下面列出了android.os.ParcelFileDescriptor#getFileDescriptor ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static boolean saveFile(Context context, Uri file, byte[] data) {
boolean success = true;
try {
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(file, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(data);
fileOutputStream.close();
pfd.close();
} catch (IOException e) {
e.printStackTrace();
success = false;
}
return success;
}
@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);
}
/**
* This method extracts all data from the incoming intent and setups views properly.
*/
private void setImageData(@NonNull Intent intent) {
Uri inputUri = intent.getParcelableExtra(UCropMulti.EXTRA_INPUT_URI);
Uri outputUri = intent.getParcelableExtra(UCropMulti.EXTRA_OUTPUT_URI);
processOptions(intent);
if (inputUri != null && outputUri != null) {
try {
ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(inputUri, "r");
FileInputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
String suffix = FileUtils.extSuffix(inputStream);
boolean isGif = FileUtils.isGifForSuffix(suffix);
mGestureCropImageView.setRotateEnabled(isGif ? false : rotateEnabled);
mGestureCropImageView.setScaleEnabled(isGif ? false : scaleEnabled);
mGestureCropImageView.setImageUri(inputUri, outputUri);
} catch (Exception e) {
setResultError(e);
closeActivity();
}
} else {
setResultError(new NullPointerException(getString(R.string.ucrop_error_input_data_is_absent)));
closeActivity();
}
}
/**
* 根据相对路径获取图片宽高
*
* @param c 上下文
* @param uri 图片uri地址
* @return 宽高信息
*/
public static int[] getImageWidthHeight(Context c, Uri uri) {
try {
ParcelFileDescriptor parcelFileDescriptor = c.getContentResolver()
.openFileDescriptor(uri, "r");
if (parcelFileDescriptor != null) {
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return new int[]{image.getWidth(), image.getHeight()};
}
} catch (Exception e) {
e.printStackTrace();
}
return new int[]{0, 0};
}
public static Bitmap getBitmapFromUri(Context c, Uri uri) {
try {
ParcelFileDescriptor parcelFileDescriptor = c.getContentResolver()
.openFileDescriptor(uri, "r");
if (parcelFileDescriptor != null) {
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据相对路径获取图片宽高
*
* @param c 上下文
* @param uri 图片uri地址
* @return 宽高信息
*/
public static int[] getImageWidthHeight(Context c, Uri uri) {
try {
ParcelFileDescriptor parcelFileDescriptor = c.getContentResolver()
.openFileDescriptor(uri, "r");
if (parcelFileDescriptor != null) {
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return new int[]{image.getWidth(), image.getHeight()};
}
} catch (Exception e) {
e.printStackTrace();
}
return new int[]{0, 0};
}
@SuppressFBWarnings(value = {"OS_OPEN_STREAM"}, justification = "Closed by backup system")
@SuppressWarnings("unchecked")
public BackupState(ParcelFileDescriptor parceledState) throws IOException {
if (parceledState == null) return;
try {
FileInputStream instream = new FileInputStream(parceledState.getFileDescriptor());
ObjectInputStream in = new ObjectInputStream(instream);
mNames = (ArrayList<String>) in.readObject();
mValues = (ArrayList<byte[]>) in.readObject();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* コンストラクタ
* @param context
* @param mimeType
* @param relativePath
* @param nameWithExt
* @param dataPath
* @throws FileNotFoundException
*/
public MediaStoreOutputStream(@NonNull final Context context,
@Nullable final String mimeType,
@Nullable final String relativePath,
@NonNull final String nameWithExt,
@Nullable final String dataPath)
throws FileNotFoundException {
mCr = context.getContentResolver();
mUri = MediaStoreUtils.getContentUri(mCr, mimeType, relativePath, nameWithExt, dataPath);
final ParcelFileDescriptor pfd = mCr.openFileDescriptor(mUri, "rw");
mOutputStream = new FileOutputStream(pfd.getFileDescriptor());
mOutputPath = UriHelper.getPath(context, mUri);
}
public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
Uri uri, ContentResolver cr, ParcelFileDescriptor pfd,
BitmapFactory.Options options) {
try {
if (pfd == null) pfd = makeInputStream(uri, cr);
if (pfd == null) return null;
if (options == null) options = new BitmapFactory.Options();
FileDescriptor fd = pfd.getFileDescriptor();
options.inJustDecodeBounds = true;
BitmapManager.instance().decodeFileDescriptor(fd, options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return null;
}
options.inSampleSize = computeSampleSize(
options, minSideLength, maxNumOfPixels);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapManager.instance().decodeFileDescriptor(fd, options);
} catch (OutOfMemoryError ex) {
Log.e(TAG, "Got oom exception ", ex);
return null;
} finally {
closeSilently(pfd);
}
}
private FileDescriptor getFileDescriptor(Uri uri) {
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return parcelFileDescriptor.getFileDescriptor();
}
@Override
public void writeNewStateDescription(ParcelFileDescriptor newState) {
long fileModified = 0;
if(prefsFiles != null) {
prefsFiles.lastModified();
}
try {
FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
DataOutputStream out = new DataOutputStream(outstream);
out.writeLong(fileModified);
out.close();
} catch (IOException e) {
Log.e(THIS_FILE, "Cannot manage final local backup state", e);
}
}
private void writeNewState(final long dbFileModification, final ParcelFileDescriptor newState) {
// write to newState
final FileOutputStream newStateOS = new FileOutputStream(newState.getFileDescriptor());
final DataOutputStream newStateDataOS = new DataOutputStream(newStateOS);
try {
newStateDataOS.writeLong(dbFileModification);
new WorkTimeTrackerBackupManager(context).setLastBackupTimestamp(dbFileModification);
newStateDataOS.close();
} catch (IOException e) {
// error on writing the newState, ignored
}
}
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;
}
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;
}
}
public DownloadUriOutputStream(Context context, Uri uri, int bufferSize) throws
FileNotFoundException {
final ParcelFileDescriptor pdf = context.getContentResolver().openFileDescriptor(uri, "rw");
if (pdf == null) throw new FileNotFoundException("result of " + uri + " is null!");
this.pdf = pdf;
this.fos = new FileOutputStream(pdf.getFileDescriptor());
this.channel = fos.getChannel();
this.out = new BufferedOutputStream(fos, bufferSize);
}
public static boolean isEffective(Context context, Uri uri) {
try {
ParcelFileDescriptor parcelFileDescriptor =
context.getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
return options.outWidth > 0 && options.outHeight > 0;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@SuppressFBWarnings(value = {"OS_OPEN_STREAM"}, justification = "Closed by backup system")
public void save(ParcelFileDescriptor parceledState) throws IOException {
FileOutputStream outstream = new FileOutputStream(parceledState.getFileDescriptor());
ObjectOutputStream out = new ObjectOutputStream(outstream);
out.writeObject(mNames);
out.writeObject(mValues);
}
/**
* Open a stream to the content associated with a URI.
*
* <p>
* If the provided URI is not a {@code file://} URI, {@link ContentResolver#openInputStream(Uri)} is used to open a
* stream. If it is a {@code file://}, this method makes sure the file isn't owned by this app.
* </p>
*
* @param uri
* The URI pointing to the content to access.
*
* @return {@code InputStream} to access the content.
*
* @throws FileNotFoundException
* If the provided URI could not be opened or if it points to a file owned by this app.
*/
@Nullable
public InputStream openInputStream(@NotNull Uri uri) throws FileNotFoundException {
//noinspection ConstantConditions
if (uri == null) {
throw new NullPointerException("Argument 'uri' must not be null");
}
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
String authority = uri.getAuthority();
if (disallowedProviders.isDisallowed(authority)) {
throw new FileNotFoundException("content URI is owned by the application itself. " +
"Content provider is not explicitly allowed: " + authority);
}
}
if (!ContentResolver.SCHEME_FILE.equals(scheme)) {
return contentResolver.openInputStream(uri);
}
File file = new File(uri.getPath());
ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
int fileUid = getFileUidOrThrow(fileDescriptor);
if (fileUid == android.os.Process.myUid()) {
throw new FileNotFoundException("File is owned by the application itself");
}
AssetFileDescriptor fd = new AssetFileDescriptor(parcelFileDescriptor, 0, -1);
try {
return fd.createInputStream();
} catch (IOException e) {
throw new FileNotFoundException("Unable to create stream");
}
}
private void doExportToSd(Uri uri, File template)
throws IOException {
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
if (!mRepo.applyTemplate(template, mSelectedLocale, out))
throw new IOException("Apply default template failed.");
out.close();
pfd.close();
}
public static Bitmap getBitmapFromUri(Context context, Uri uri) throws IOException {
Logger(TAG, "getBitmapFromUri " + uri.toString(), false);
ParcelFileDescriptor parcelFileDescriptor =
context.getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Logger(TAG, "uri FileDescriptor : " + fileDescriptor.toString(), false);
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}