android.os.ParcelFileDescriptor源码实例Demo

类android.os.ParcelFileDescriptor源码实例Demo

下面列出了android.os.ParcelFileDescriptor 类实例代码,或者点击链接到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);
}
 
源代码2 项目: mollyim-android   文件: PartProvider.java
@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.");
}
 
源代码3 项目: mollyim-android   文件: MemoryFileDescriptor.java
/**
 * 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;
}
 
源代码4 项目: FimiX8-RE   文件: FimiMediaPlayer.java
@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();
    }
}
 
源代码5 项目: android_9.0.0_r45   文件: PackageInstaller.java
/**
 * 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");
        }
    }
}
 
源代码6 项目: revolution-irc   文件: ThemeEditorActivity.java
@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);
}
 
源代码7 项目: FireFiles   文件: UsbStorageProvider.java
@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());
        }
    }
 
源代码8 项目: xDrip-plus   文件: MtpTools.java
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();

}
 
源代码9 项目: giffun   文件: VideoBitmapDecoder.java
@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;
}
 
源代码10 项目: android-test   文件: TestStorage.java
/**
 * 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();
    }
  }
}
 
源代码11 项目: bcm-android   文件: PartProvider.java
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);
}
 
源代码12 项目: secrecy   文件: OurFileProvider.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;
}
 
源代码13 项目: xDrip   文件: MtpTools.java
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();

}
 
源代码14 项目: FireFiles   文件: StorageProvider.java
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;
}
 
源代码15 项目: android-recipes-app   文件: FileProvider.java
/**
 * 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;
}
 
源代码16 项目: Telegram   文件: CallNotificationSoundProvider.java
@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());
	}
}
 
源代码17 项目: mobly-bundled-snippets   文件: FileSnippet.java
@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();
    }
}
 
源代码18 项目: FireFiles   文件: NonMediaDocumentsProvider.java
@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);
        }
    });
}
 
源代码20 项目: Effects-Pro   文件: LocalStorageProvider.java
@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);
	}
}
 
源代码21 项目: FireFiles   文件: ParcelFileDescriptorUtil.java
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];
}
 
源代码22 项目: APDE   文件: FileSelection.java
@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;
}
 
源代码23 项目: Dashchan   文件: FileProvider.java
@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();
		}
	}
}
 
源代码24 项目: FireFiles   文件: DocumentArchiveHelper.java
/**
 * 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);
    }
}
 
源代码25 项目: libcommon   文件: MediaAVRecorder.java
/**
 * コンストラクタ
 * @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");
}
 
源代码26 项目: Shelter   文件: UriForwardProxy.java
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;
            }
        }
    };
}
 
源代码27 项目: Shelter   文件: FileShuttleService.java
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;
}
 
源代码29 项目: secrecy   文件: ObserveFileJob.java
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
    }
}
 
源代码30 项目: personaldnsfilter   文件: DNSFilterService.java
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!");
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类所在包
 同包方法