下面列出了怎么用android.os.ParcelFileDescriptor的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onCreate() {
// The name of the SharedPreferences file
final String prefs = getPackageName() + "_preferences"; // getPackageName() cannot be used in final
SharedPreferencesBackupHelper prefsHelper = new SharedPreferencesBackupHelper(this, prefs) {
@Override
public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
ParcelFileDescriptor newState) {
if (new WorkTimeTrackerBackupManager(WorkTimeTrackerBackupAgentHelper.this).isEnabled()) {
super.performBackup(oldState, data, newState);
}
}
};
addHelper(PREFS_BACKUP_KEY, prefsHelper);
DbBackupHelper dbHelper = new DbBackupHelper(this);
addHelper(DB_BACKUP_KEY, dbHelper);
}
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
Log.i(TAG, "openFile() called!");
if (KeyCachingService.isLocked(getContext())) {
Log.w(TAG, "masterSecret was null, abandoning.");
return null;
}
switch (uriMatcher.match(uri)) {
case SINGLE_ROW:
Log.i(TAG, "Parting out a single row...");
try {
final PartUriParser partUri = new PartUriParser(uri);
return getParcelStreamForAttachment(partUri.getPartId());
} catch (IOException ioe) {
Log.w(TAG, ioe);
throw new FileNotFoundException("Error opening file");
}
}
throw new FileNotFoundException("Request for bad part.");
}
/**
* Does this device support memory file descriptor.
*/
public synchronized static boolean supported() {
if (supported == null) {
try {
int fileDescriptor = FileUtils.createMemoryFileDescriptor("CHECK");
if (fileDescriptor < 0) {
supported = false;
Log.w(TAG, "MemoryFileDescriptor is not available.");
} else {
supported = true;
ParcelFileDescriptor.adoptFd(fileDescriptor).close();
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
return supported;
}
@TargetApi(13)
public void setDataSource(FileDescriptor fd) throws IOException, IllegalArgumentException, IllegalStateException {
if (VERSION.SDK_INT < 12) {
try {
Field f = fd.getClass().getDeclaredField("descriptor");
f.setAccessible(true);
_setDataSourceFd(f.getInt(fd));
return;
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e2) {
throw new RuntimeException(e2);
}
}
ParcelFileDescriptor pfd = ParcelFileDescriptor.dup(fd);
try {
_setDataSourceFd(pfd.getFd());
} finally {
pfd.close();
}
}
/**
* Ensure that any outstanding data for given stream has been committed
* to disk. This is only valid for streams returned from
* {@link #openWrite(String, long, long)}.
*/
public void fsync(@NonNull OutputStream out) throws IOException {
if (ENABLE_REVOCABLE_FD) {
if (out instanceof ParcelFileDescriptor.AutoCloseOutputStream) {
try {
Os.fsync(((ParcelFileDescriptor.AutoCloseOutputStream) out).getFD());
} catch (ErrnoException e) {
throw e.rethrowAsIOException();
}
} else {
throw new IllegalArgumentException("Unrecognized stream");
}
} else {
if (out instanceof FileBridge.FileBridgeOutputStream) {
((FileBridge.FileBridgeOutputStream) out).fsync();
} else {
throw new IllegalArgumentException("Unrecognized stream");
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_EXPORT) {
if (data == null || data.getData() == null)
return;
try {
Uri uri = data.getData();
ParcelFileDescriptor desc = getContentResolver().openFileDescriptor(uri, "w");
BufferedWriter wr = new BufferedWriter(new FileWriter(desc.getFileDescriptor()));
ThemeManager.getInstance(this).exportTheme(getThemeInfo(), wr);
wr.close();
desc.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, R.string.error_generic, Toast.LENGTH_SHORT).show();
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal) throws FileNotFoundException {
try {
UsbFile file = getFileForDocId(documentId);
/* final int accessMode = ParcelFileDescriptorUtil.parseMode(mode);
if ((accessMode | ParcelFileDescriptor.MODE_READ_ONLY) == ParcelFileDescriptor.MODE_READ_ONLY) {
return ParcelFileDescriptorUtil.pipeFrom(new UsbFileInputStream(file));
} else if ((accessMode | ParcelFileDescriptor.MODE_WRITE_ONLY) == ParcelFileDescriptor.MODE_WRITE_ONLY) {
return ParcelFileDescriptorUtil.pipeTo(new UsbFileOutputStream(file));
}*/
final boolean isWrite = (mode.indexOf('w') != -1);
if (isWrite) {
return ParcelFileDescriptorUtil.pipeTo(new UsbFileOutputStream(file));
} else {
return ParcelFileDescriptorUtil.pipeFrom(new UsbFileInputStream(file));
}
} catch (IOException e) {
throw new FileNotFoundException(e.getMessage());
}
}
private static synchronized int createDocument(final MtpDevice device, final MtpObjectInfo objectInfo,
final ParcelFileDescriptor source) {
final MtpObjectInfo sendObjectInfoResult = device.sendObjectInfo(objectInfo);
if (sendObjectInfoResult == null) {
Log.e(TAG, "Null sendObjectInfoResult in create document :(");
return -1;
}
Log.d(TAG, "Send object info result: " + sendObjectInfoResult.getName());
// Association is what passes for a folder within mtp
if (objectInfo.getFormat() != MtpConstants.FORMAT_ASSOCIATION) {
if (!device.sendObject(sendObjectInfoResult.getObjectHandle(),
sendObjectInfoResult.getCompressedSize(), source)) {
return -1;
}
}
Log.d(TAG, "Success indicated with handle: " + sendObjectInfoResult.getObjectHandle());
return sendObjectInfoResult.getObjectHandle();
}
@Override
public Bitmap decode(ParcelFileDescriptor resource, BitmapPool bitmapPool, int outWidth, int outHeight,
DecodeFormat decodeFormat)
throws IOException {
MediaMetadataRetriever mediaMetadataRetriever = factory.build();
mediaMetadataRetriever.setDataSource(resource.getFileDescriptor());
Bitmap result;
if (frame >= 0) {
result = mediaMetadataRetriever.getFrameAtTime(frame);
} else {
result = mediaMetadataRetriever.getFrameAtTime();
}
mediaMetadataRetriever.release();
resource.close();
return result;
}
/**
* Gets the output stream for a given Uri.
*
* <p>The returned OutputStream is essentially a {@link java.io.FileOutputStream} which likely
* should be buffered to avoid {@code UnbufferedIoViolation} when running under strict mode.
*
* @param uri The Uri for which the OutputStream is required.
*/
OutputStream getOutputStream(Uri uri) throws FileNotFoundException {
checkNotNull(uri);
ContentProviderClient providerClient = null;
try {
providerClient = makeContentProviderClient(contentResolver, uri);
return new ParcelFileDescriptor.AutoCloseOutputStream(providerClient.openFile(uri, "w"));
} catch (RemoteException re) {
throw new TestStorageException("Unable to access content provider: " + uri, re);
} finally {
if (providerClient != null) {
// Uses #release() to be compatible with API < 24.
providerClient.release();
}
}
}
private ParcelFileDescriptor getParcelStreamForAttachment(MasterSecret masterSecret, AttachmentId attachmentId) throws IOException {
AttachmentRepo repo = Repository.getAttachmentRepo(AMELogin.INSTANCE.getMajorContext());
if (repo == null) {
ALog.w(TAG, "AttachmentRepo is null!");
return null;
}
InputStream stream = repo.getAttachmentStream(masterSecret, attachmentId.getRowId(), attachmentId.getUniqueId(), 0);
if (stream == null) {
throw new FileNotFoundException("Attachment file not found");
}
long plaintextLength = Util.getStreamLength(stream);
MemoryFile memoryFile = new MemoryFile(attachmentId.toString(), Util.toIntExact(plaintextLength));
InputStream in = repo.getAttachmentStream(masterSecret, attachmentId.getRowId(), attachmentId.getUniqueId(), 0);
OutputStream out = memoryFile.getOutputStream();
Util.copy(in, out);
Util.close(out);
Util.close(in);
return MemoryFileUtil.getParcelFileDescriptor(memoryFile);
}
private static int modeToMode(String mode) {
int modeBits;
if ("r".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
} else if ("w".equals(mode) || "wt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else if ("wa".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_APPEND;
} else if ("rw".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE;
} else if ("rwt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
return modeBits;
}
private static synchronized int createDocument(final MtpDevice device, final MtpObjectInfo objectInfo,
final ParcelFileDescriptor source) {
final MtpObjectInfo sendObjectInfoResult = device.sendObjectInfo(objectInfo);
if (sendObjectInfoResult == null) {
Log.e(TAG, "Null sendObjectInfoResult in create document :(");
return -1;
}
Log.d(TAG, "Send object info result: " + sendObjectInfoResult.getName());
// Association is what passes for a folder within mtp
if (objectInfo.getFormat() != MtpConstants.FORMAT_ASSOCIATION) {
if (!device.sendObject(sendObjectInfoResult.getObjectHandle(),
sendObjectInfoResult.getCompressedSize(), source)) {
return -1;
}
}
Log.d(TAG, "Success indicated with handle: " + sendObjectInfoResult.getObjectHandle());
return sendObjectInfoResult.getObjectHandle();
}
protected ParcelFileDescriptor openImageThumbnailCleared(long id, CancellationSignal signal)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(Images.Thumbnails.EXTERNAL_CONTENT_URI,
ImageThumbnailQuery.PROJECTION, Images.Thumbnails.IMAGE_ID + "=" + id, null,
null);
if (cursor.moveToFirst()) {
final String data = cursor.getString(ImageThumbnailQuery._DATA);
return ParcelFileDescriptor.open(
new File(data), ParcelFileDescriptor.MODE_READ_ONLY);
}
} finally {
IoUtils.closeQuietly(cursor);
}
return null;
}
/**
* Copied from ContentResolver.java
*/
private static int modeToMode(String mode) {
int modeBits;
if ("r".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
} else if ("w".equals(mode) || "wt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else if ("wa".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_APPEND;
} else if ("rw".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE;
} else if ("rwt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
return modeBits;
}
@Nullable
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException{
if(!"r".equals(mode))
throw new SecurityException("Unexpected file mode "+mode);
if(ApplicationLoader.applicationContext==null)
throw new FileNotFoundException("Unexpected application state");
VoIPBaseService srv=VoIPBaseService.getSharedInstance();
if(srv!=null){
srv.startRingtoneAndVibration();
}
try{
ParcelFileDescriptor[] pipe=ParcelFileDescriptor.createPipe();
ParcelFileDescriptor.AutoCloseOutputStream outputStream = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);
byte[] silentWav={82,73,70,70,41,0,0,0,87,65,86,69,102,109,116,32,16,0,0,0,1,0,1,0,68,(byte)172,0,0,16,(byte)177,2,0,2,0,16,0,100,97,116,97,10,0,0,0,0,0,0,0,0,0,0,0,0,0};
outputStream.write(silentWav);
outputStream.close();
return pipe[0];
}catch(IOException x){
throw new FileNotFoundException(x.getMessage());
}
}
@Rpc(description = "Compute MD5 hash on a content URI. Return the MD5 has has a hex string.")
public String fileMd5Hash(String uri) throws IOException, NoSuchAlgorithmException {
Uri uri_ = Uri.parse(uri);
ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri_, "r");
MessageDigest md = MessageDigest.getInstance("MD5");
int length = (int) pfd.getStatSize();
byte[] buf = new byte[length];
ParcelFileDescriptor.AutoCloseInputStream stream =
new ParcelFileDescriptor.AutoCloseInputStream(pfd);
DigestInputStream dis = new DigestInputStream(stream, md);
try {
dis.read(buf, 0, length);
return Utils.bytesToHexString(md.digest());
} finally {
dis.close();
stream.close();
}
}
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
throws FileNotFoundException {
if (!"r".equals(mode)) {
throw new IllegalArgumentException("Media is read-only");
}
final Uri target = getUriForDocumentId(docId);
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
return getContext().getContentResolver().openFileDescriptor(target, mode);
} finally {
Binder.restoreCallingIdentity(token);
}
}
public WriteFileAsyncTask(ParcelFileDescriptor destination,
CancellationSignal cancellationSignal, WriteResultCallback callback) {
mDestination = destination;
mResultCallback = callback;
mCancellationSignal = cancellationSignal;
mCancellationSignal.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel() {
cancel(true);
}
});
}
@Override
public ParcelFileDescriptor openDocument(final String documentId, final String mode,
final CancellationSignal signal) throws FileNotFoundException {
File file = new File(documentId);
final boolean isWrite = (mode.indexOf('w') != -1);
if (isWrite) {
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
} else {
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
}
public static ParcelFileDescriptor pipeFrom(InputStream inputStream)
throws IOException {
final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
final OutputStream output = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);
new TransferThread(inputStream, output).start();
return pipe[0];
}
@NonNull
public static List<ParcelFileDescriptor> getSelectedFds(Context context, Intent intent, Mode mode) {
List<Uri> uris = getSelectedUris(intent);
List<ParcelFileDescriptor> fds = new ArrayList<>();
for (Uri uri : uris) {
ParcelFileDescriptor fd = openUri(context, uri, mode);
if (fd != null) {
fds.add(fd);
}
}
return fds;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
switch (URI_MATCHER.match(uri)) {
case URI_UPDATES: {
if (!"r".equals(mode)) {
throw new FileNotFoundException();
}
File file = getUpdatesFile(getContext(), uri.getLastPathSegment());
if (file != null) {
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
}
case URI_DOWNLOADS: {
if (downloadsFile != null && uri.equals(downloadsFile.uri)) {
return ParcelFileDescriptor.open(downloadsFile.file, ParcelFileDescriptor.MODE_READ_ONLY);
}
}
case URI_SHARE: {
if (shareFile != null && uri.equals(shareFile.uri)) {
return ParcelFileDescriptor.open(shareFile.file, ParcelFileDescriptor.MODE_READ_ONLY);
}
}
default: {
throw new FileNotFoundException();
}
}
}
/**
* Opens a file within an archive.
*
*/
public ParcelFileDescriptor openDocument(
String documentId, String mode, final CancellationSignal signal)
throws FileNotFoundException {
Loader loader = null;
try {
loader = obtainInstance(documentId);
return loader.get().openDocument(documentId, mode, signal);
} finally {
releaseInstance(loader);
}
}
/**
* コンストラクタ
* @param context
* @param callback
* @param config
* @param saveTreeId 0: SAFを使わない, それ以外: SAFのツリーIDとみなして処理を試みる
* @param dirs savedTreeIdが示すディレクトリからの相対ディレクトリパス, nullならsavedTreeIdが示すディレクトリ
* @param fileName
* @param factory
* @throws IOException
*/
public MediaAVRecorder(@NonNull final Context context,
@Nullable final RecorderCallback callback,
@Nullable final VideoConfig config,
@Nullable final IMuxer.IMuxerFactory factory,
final int saveTreeId, @Nullable final String dirs, @NonNull final String fileName) throws IOException {
super(context, callback, config, factory);
mSaveTreeId = saveTreeId;
if ((saveTreeId > 0) && SAFUtils.hasPermission(context, saveTreeId)) {
DocumentFile tree = SAFUtils.getFile(context,
saveTreeId, dirs, "*/*", fileName);
if (tree != null) {
mOutputPath = UriHelper.getPath(context, tree.getUri());
final ParcelFileDescriptor pfd
= context.getContentResolver().openFileDescriptor(
tree.getUri(), "rw");
try {
if (pfd != null) {
setupMuxer(pfd.getFd());
return;
} else {
// ここには来ないはずだけど
throw new IOException("could not create ParcelFileDescriptor");
}
} catch (final Exception e) {
if (pfd != null) {
pfd.close();
}
throw e;
}
}
}
// フォールバックはしない
throw new IOException("path not found/can't write");
}
public UriForwardProxy(Context context, Uri uri) {
ContentResolver resolver = context.getContentResolver();
mOpener = new IUriOpener.Stub() {
@Override
public ParcelFileDescriptor openFile(String mode) {
try {
return resolver.openFileDescriptor(uri, mode);
} catch (FileNotFoundException e) {
return null;
}
}
};
}
private ParcelFileDescriptor loadVideoThumbnail(String fullPath) {
// The MediaStore interface for video thumbnails just do not work at all
// It can't even retrieve video IDs from the database
// Anyway, use this as a temporary fix.
// TODO: Figure out how to use the MediaStore interface with videos
Bitmap bmp = ThumbnailUtils.createVideoThumbnail(fullPath, MediaStore.Video.Thumbnails.MINI_KIND);
return bitmapToFd(bmp);
}
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;
}
public void setup(java.io.File file) {
this.file = file;
try {
pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_WRITE_ONLY);
size = file.length();
} catch (IOException ignored) {
//FINEE
}
}
private VPNRunner(int id, ParcelFileDescriptor vpnInterface){
this.id=id;
this.vpnInterface= vpnInterface;
in = new FileInputStream(vpnInterface.getFileDescriptor());
out = new FileOutputStream(vpnInterface.getFileDescriptor());
Logger.getLogger().logLine("VPN Connected!");
}