Java Code Examples for android.os.ParcelFileDescriptor

The following are top voted examples for showing how to use android.os.ParcelFileDescriptor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: FireFiles   File: StorageProvider.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 2
Project: react-native-videoplayer   File: APEZProvider.java   Source Code and License 6 votes vote down vote up
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
		throws FileNotFoundException {
       initIfNecessary();
	AssetFileDescriptor af = openAssetFile(uri, mode);
	if ( null != af ) {
		return af.getParcelFileDescriptor();
	}
	return null;
}
 
Example 3
Project: chromium-net-for-android   File: Linker.java   Source Code and License 6 votes vote down vote up
@Override
public void writeToParcel(Parcel out, int flags) {
    if (mRelroFd >= 0) {
        out.writeLong(mLoadAddress);
        out.writeLong(mLoadSize);
        out.writeLong(mRelroStart);
        out.writeLong(mRelroSize);
        try {
            ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd);
            fd.writeToParcel(out, 0);
            fd.close();
        } catch (java.io.IOException e) {
            Log.e(TAG, "Can't write LibInfo file descriptor to parcel", e);
        }
    }
}
 
Example 4
Project: container   File: PackageInstallerSession.java   Source Code and License 6 votes vote down vote up
private ParcelFileDescriptor openReadInternal(String name) throws IOException {
    assertPreparedAndNotSealed("openRead");

    try {
        if (!FileUtils.isValidExtFilename(name)) {
            throw new IllegalArgumentException("Invalid name: " + name);
        }
        final File target = new File(resolveStageDir(), name);

        final FileDescriptor targetFd = Os.open(target.getAbsolutePath(), O_RDONLY, 0);
        return ParcelFileDescriptor.dup(targetFd);

    } catch (ErrnoException e) {
        throw new IOException(e);
    }
}
 
Example 5
Project: mobly-bundled-snippets   File: FileSnippet.java   Source Code and License 6 votes vote down vote up
@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();
    }
}
 
Example 6
Project: easyfilemanager   File: StorageProvider.java   Source Code and License 6 votes vote down vote up
protected AssetFileDescriptor openVideoThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = null;
    try {
        cursor = resolver.query(Video.Thumbnails.EXTERNAL_CONTENT_URI,
                VideoThumbnailQuery.PROJECTION, Video.Thumbnails.VIDEO_ID + "=" + id, null,
                null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(VideoThumbnailQuery._DATA);
            return new AssetFileDescriptor(ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY), 0,
                    AssetFileDescriptor.UNKNOWN_LENGTH);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example 7
Project: GitHub   File: FileLoader.java   Source Code and License 6 votes vote down vote up
public FileDescriptorFactory() {
  super(new FileOpener<ParcelFileDescriptor>() {
    @Override
    public ParcelFileDescriptor open(File file) throws FileNotFoundException {
      return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    }

    @Override
    public void close(ParcelFileDescriptor parcelFileDescriptor) throws IOException {
      parcelFileDescriptor.close();
    }

    @Override
    public Class<ParcelFileDescriptor> getDataClass() {
      return ParcelFileDescriptor.class;
    }
  });
}
 
Example 8
Project: Phial   File: FileProvider.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Project: easyfilemanager   File: StorageProvider.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 10
Project: GitHub   File: FileDescriptorLocalUriFetcherTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testLoadResource_returnsFileDescriptor() throws Exception {
  Context context = RuntimeEnvironment.application;
  Uri uri = Uri.parse("file://nothing");

  ContentResolver contentResolver = context.getContentResolver();
  ContentResolverShadow shadow = Shadow.extract(contentResolver);

  AssetFileDescriptor assetFileDescriptor = mock(AssetFileDescriptor.class);
  ParcelFileDescriptor parcelFileDescriptor = mock(ParcelFileDescriptor.class);
  when(assetFileDescriptor.getParcelFileDescriptor()).thenReturn(parcelFileDescriptor);
  shadow.registerFileDescriptor(uri, assetFileDescriptor);

  FileDescriptorLocalUriFetcher fetcher =
      new FileDescriptorLocalUriFetcher(context.getContentResolver(), uri);
  fetcher.loadData(Priority.NORMAL, callback);
  verify(callback).onDataReady(eq(parcelFileDescriptor));
}
 
Example 11
Project: kognitivo   File: FacebookContentProvider.java   Source Code and License 6 votes vote down vote up
@Override
public android.os.ParcelFileDescriptor openFile(android.net.Uri uri, java.lang.String mode)
        throws java.io.FileNotFoundException {

    Pair<UUID, String> callIdAndAttachmentName = parseCallIdAndAttachmentName(uri);
    if (callIdAndAttachmentName == null) {
        throw new FileNotFoundException();
    }

    try {
        File file = NativeAppCallAttachmentStore.openAttachment(
                callIdAndAttachmentName.first,
                callIdAndAttachmentName.second);

        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    } catch (FileNotFoundException exception) {
        Log.e(TAG, "Got unexpected exception:" + exception);
        throw exception;
    }
}
 
Example 12
Project: kognitivo   File: VideoUploader.java   Source Code and License 6 votes vote down vote up
private void initialize()
        throws FileNotFoundException {
    ParcelFileDescriptor fileDescriptor = null;
    try {
        if (Utility.isFileUri(videoUri)) {
            fileDescriptor = ParcelFileDescriptor.open(
                    new File(videoUri.getPath()),
                    ParcelFileDescriptor.MODE_READ_ONLY);
            videoSize = fileDescriptor.getStatSize();
            videoStream = new ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor);
        } else if (Utility.isContentUri(videoUri)) {
            videoSize = Utility.getContentSize(videoUri);
            videoStream = FacebookSdk
                    .getApplicationContext()
                    .getContentResolver()
                    .openInputStream(videoUri);
        } else {
            throw new FacebookException("Uri must be a content:// or file:// uri");
        }
    } catch (FileNotFoundException e) {
        Utility.closeQuietly(videoStream);

        throw e;
    }
}
 
Example 13
Project: Cable-Android   File: PartProvider.java   Source Code and License 6 votes vote down vote up
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
  final MasterSecret masterSecret = KeyCachingService.getMasterSecret(getContext());
  Log.w(TAG, "openFile() called!");

  if (masterSecret == null) {
    Log.w(TAG, "masterSecret was null, abandoning.");
    return null;
  }

  switch (uriMatcher.match(uri)) {
  case SINGLE_ROW:
    Log.w(TAG, "Parting out a single row...");
    try {
      final PartUriParser partUri = new PartUriParser(uri);
      return getParcelStreamForAttachment(masterSecret, partUri.getPartId());
    } catch (IOException ioe) {
      Log.w(TAG, ioe);
      throw new FileNotFoundException("Error opening file");
    }
  }

  throw new FileNotFoundException("Request for bad part.");
}
 
Example 14
Project: simple-share-android   File: StorageProvider.java   Source Code and License 6 votes vote down vote up
protected AssetFileDescriptor openVideoThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = null;
    try {
        cursor = resolver.query(Video.Thumbnails.EXTERNAL_CONTENT_URI,
                VideoThumbnailQuery.PROJECTION, Video.Thumbnails.VIDEO_ID + "=" + id, null,
                null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(VideoThumbnailQuery._DATA);
            return new AssetFileDescriptor(ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY), 0,
                    AssetFileDescriptor.UNKNOWN_LENGTH);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example 15
Project: FireFiles   File: MediaDocumentsProvider.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 16
Project: easyfilemanager   File: Utils.java   Source Code and License 6 votes vote down vote up
public static int parseMode(String mode) {
    final 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("Bad mode '" + mode + "'");
    }
    return modeBits;
}
 
Example 17
Project: easyfilemanager   File: NonMediaDocumentsProvider.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 18
Project: NotifyTools   File: PdfActivity.java   Source Code and License 5 votes vote down vote up
private void openRenderer( )  {
    // In this sample, we read a PDF from the assets directory.
    File f = new File(uri.getPath());
    try {
        mFileDescriptor = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
        mPdfRenderer = new PdfRenderer(mFileDescriptor);
        cnt=mPdfRenderer.getPageCount();
    } catch (Exception e) {
        log.e(e);
    }
}
 
Example 19
Project: q-mail   File: AttachmentProvider.java   Source Code and License 5 votes vote down vote up
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
    List<String> segments = uri.getPathSegments();
    String accountUuid = segments.get(0);
    String attachmentId = segments.get(1);

    ParcelFileDescriptor parcelFileDescriptor = openAttachment(accountUuid, attachmentId);
    if (parcelFileDescriptor == null) {
        throw new FileNotFoundException("Attachment missing or cannot be opened!");
    }
    return parcelFileDescriptor;
}
 
Example 20
Project: ThunderMusic   File: ImageUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Return album artwork given the id
 * if nothing is found, we try a downloaded one
 *
 * @param context
 * @param album_id
 * @return
 */
public static Bitmap getArtworkQuick_Base1(Context context, long album_id) {
    if (album_id != -1) {
        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(MusicUtils.sArtworkUri, album_id);
        if (uri != null) {
            // ParcelFileDescriptor fd = null;
            try {

                ParcelFileDescriptor fd = res.openFileDescriptor(uri, "r");

                BitmapFactory.Options o2 = new BitmapFactory.Options();

                o2.inSampleSize = 2;
                o2.inDither = false;
                o2.inPreferredConfig = Bitmap.Config.RGB_565;

                Bitmap b = BitmapFactory.decodeFileDescriptor(
                        fd.getFileDescriptor(), null, o2);

                if (b != null) {
                    return b;
                } else {
                    b = getArtworkDownloadedResized(context, album_id);
                    if (b != null) {
                        return b;
                    } else {
                        return null;
                    }
                }
            } catch (FileNotFoundException e) {
                return null;
            }
        }
    }
    return null;
}
 
Example 21
Project: backup   File: ContentProviderRestoreComponent.java   Source Code and License 5 votes vote down vote up
private int transferIncrementalRestoreData(String packageName, ParcelFileDescriptor outputFileDescriptor)
        throws IOException, InvalidAlgorithmParameterException, InvalidKeyException {

    ParcelFileDescriptor inputFileDescriptor = buildInputFileDescriptor();
    ZipInputStream inputStream = buildInputStream(inputFileDescriptor);
    BackupDataOutput backupDataOutput = new BackupDataOutput(outputFileDescriptor.getFileDescriptor());

    Optional<ZipEntry> zipEntryOptional = seekToEntry(inputStream,
            configuration.getIncrementalBackupDirectory() + packageName);
    while (zipEntryOptional.isPresent()) {
        String fileName = new File(zipEntryOptional.get().getName()).getName();
        String blobKey = new String(Base64.decode(fileName, Base64.DEFAULT));

        byte[] backupData = Streams.readFullyNoClose(inputStream);
        backupDataOutput.writeEntityHeader(blobKey, backupData.length);
        backupDataOutput.writeEntityData(backupData, backupData.length);
        inputStream.closeEntry();

        zipEntryOptional = seekToEntry(inputStream, configuration.getIncrementalBackupDirectory() + packageName);
    }

    IoUtils.closeQuietly(inputFileDescriptor);
    IoUtils.closeQuietly(outputFileDescriptor);
    return TRANSPORT_OK;
}
 
Example 22
Project: q-mail   File: ParcelFileDescriptorUtil.java   Source Code and License 5 votes vote down vote up
public static <T> DataSinkTransferThread<T> asyncPipeToDataSink(
        SMimeDataSink<T> dataSink, ParcelFileDescriptor output) throws IOException {
    InputStream inputStream = new BufferedInputStream(new AutoCloseInputStream(output));
    DataSinkTransferThread<T> dataSinkTransferThread =
            new DataSinkTransferThread<T>(dataSink, inputStream);
    dataSinkTransferThread.start();
    return dataSinkTransferThread;
}
 
Example 23
Project: prevent   File: ActivityManagerService.java   Source Code and License 5 votes vote down vote up
public final int startActivity(IApplicationThread caller, String callingPackage,
                               Intent intent, String resolvedType, IBinder resultTo,
                               String resultWho, int requestCode, int startFlags,
                               String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
    return PreventRunningUtils.onStartActivity(
            startActivity$Pr(caller, callingPackage,
                    intent, resolvedType, resultTo,
                    resultWho, requestCode, startFlags,
                    profileFile, profileFd, options),
            caller, callingPackage, intent);
}
 
Example 24
Project: q-mail   File: ParcelFileDescriptorUtil.java   Source Code and License 5 votes vote down vote up
public static ParcelFileDescriptor pipeFrom(InputStream inputStream)
        throws IOException {
    ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
    ParcelFileDescriptor readSide = pipe[0];
    ParcelFileDescriptor writeSide = pipe[1];

    new TransferThread(inputStream, new ParcelFileDescriptor.AutoCloseOutputStream(writeSide))
            .start();

    return readSide;
}
 
Example 25
Project: q-mail   File: ParcelFileDescriptorUtil.java   Source Code and License 5 votes vote down vote up
public static TransferThread pipeTo(OutputStream outputStream, ParcelFileDescriptor output)
        throws IOException {

    AutoCloseInputStream InputStream = new AutoCloseInputStream(output);
    TransferThread t = new TransferThread(InputStream, outputStream);

    t.start();
    return t;
}
 
Example 26
Project: container   File: PackageInstallerSession.java   Source Code and License 5 votes vote down vote up
private ParcelFileDescriptor openWriteInternal(String name, long offsetBytes, long lengthBytes)
        throws IOException {
    // Quick sanity check of state, and allocate a pipe for ourselves. We
    // then do heavy disk allocation outside the lock, but this open pipe
    // will block any attempted install transitions.
    final FileBridge bridge;
    synchronized (mLock) {
        assertPreparedAndNotSealed("openWrite");

        bridge = new FileBridge();
        mBridges.add(bridge);
    }
    try {
        final File target = new File(resolveStageDir(), name);
        // TODO: this should delegate to DCS so the system process avoids
        // holding open FDs into containers.
        final FileDescriptor targetFd = Os.open(target.getAbsolutePath(),
                O_CREAT | O_WRONLY, 0644);
        // If caller specified a total length, allocate it for them. Free up
        // cache space to grow, if needed.
        if (lengthBytes > 0) {
            Os.posix_fallocate(targetFd, 0, lengthBytes);
        }
        if (offsetBytes > 0) {
            Os.lseek(targetFd, offsetBytes, OsConstants.SEEK_SET);
        }
        bridge.setTargetFile(targetFd);
        bridge.start();
        return ParcelFileDescriptor.dup(bridge.getClientSocket());

    } catch (ErrnoException e) {
        throw new IOException(e);
    }
}
 
Example 27
Project: simple-share-android   File: DocumentsProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Implementation is provided by the parent class. Cannot be overriden.
 *
 * @see #openDocument(String, String, CancellationSignal)
 */
@Override
public final AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    enforceTree(uri);
    final ParcelFileDescriptor fd = openDocument(getDocumentId(uri), mode, signal);
    return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
}
 
Example 28
Project: q-mail   File: OpenPgpApi.java   Source Code and License 5 votes vote down vote up
private static void closeLoudly(ParcelFileDescriptor input) {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e);
        }
    }
}
 
Example 29
Project: vanilla-music-cover-fetch   File: CoverShowActivity.java   Source Code and License 5 votes vote down vote up
private boolean loadFromTag() {
    Uri imgLink = getIntent().getParcelableExtra(EXTRA_PARAM_P2P_VAL);
    try {
        ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(imgLink, "r");
        if (pfd == null) {
            return false;
        }

        Bitmap raw = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
        if (raw == null) {
            return false;
        }

        setCoverImage(raw);
        return true;
    } catch (FileNotFoundException e) {
        Log.e(LOG_TAG, "Passed Uri points to invalid fd! " + imgLink, e);
    }
    return false;
}
 
Example 30
Project: aos-MediaLib   File: VideoProvider.java   Source Code and License 5 votes vote down vote up
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
        throws FileNotFoundException {

    ParcelFileDescriptor pfd = null;
    int match = URI_MATCHER.match(uri);

    // let scraper handle it's part
    if (ScraperProvider.handles(match))
        return mScraperProvider.openFile(uri, mode);

    try {
        pfd = openFileHelper(uri, mode);
    } catch (FileNotFoundException ex) {
        if (mode.contains("w")) {
            // if the file couldn't be created, we shouldn't extract album art
            throw ex;
        }

        if (pfd == null) {
            throw ex;
        }
    }
    return pfd;
}
 
Example 31
Project: buildAPKsSamples   File: ExampleAgent.java   Source Code and License 5 votes vote down vote up
/**
 * Write out the new state file:  the version number, followed by the
 * three bits of data as we sent them off to the backup transport.
 */
void writeStateFile(ParcelFileDescriptor stateFile) throws IOException {
    FileOutputStream outstream = new FileOutputStream(stateFile.getFileDescriptor());
    DataOutputStream out = new DataOutputStream(outstream);

    out.writeInt(AGENT_VERSION);
    out.writeInt(mFilling);
    out.writeBoolean(mAddMayo);
    out.writeBoolean(mAddTomato);
}
 
Example 32
Project: GitHub   File: FileDescriptorLocalUriFetcher.java   Source Code and License 5 votes vote down vote up
@Override
protected ParcelFileDescriptor loadResource(Uri uri, ContentResolver contentResolver)
    throws FileNotFoundException {
  AssetFileDescriptor assetFileDescriptor = contentResolver.openAssetFileDescriptor(uri, "r");
  if (assetFileDescriptor == null) {
    throw new FileNotFoundException("FileDescriptor is null for: " + uri);
  }
  return assetFileDescriptor.getParcelFileDescriptor();
}
 
Example 33
Project: samba-documents-provider   File: ReadFileTask.java   Source Code and License 5 votes vote down vote up
ReadFileTask(String uri, SmbClient client, ParcelFileDescriptor pfd,
    ByteBufferPool bufferPool) {
  mUri = uri;
  mClient = client;
  mPfd = pfd;
  mBufferPool = bufferPool;
}
 
Example 34
Project: easyfilemanager   File: StorageProvider.java   Source Code and License 5 votes vote down vote up
protected ParcelFileDescriptor openAudioThumbnailCleared(long id, CancellationSignal signal)
        throws FileNotFoundException {
    final ContentResolver resolver = getContext().getContentResolver();

    Cursor cursor = null;
    try {
        cursor = resolver.query(Audio.Albums.EXTERNAL_CONTENT_URI,
        		AudioThumbnailQuery.PROJECTION, Audio.Albums._ID + "=" + id,
                null, null);
        if (cursor.moveToFirst()) {
            final String data = cursor.getString(AudioThumbnailQuery._DATA);
            return ParcelFileDescriptor.open(
                    new File(data), ParcelFileDescriptor.MODE_READ_ONLY);
        }
    } finally {
        IoUtils.closeQuietly(cursor);
    }
    return null;
}
 
Example 35
Project: TPlayer   File: IOUtils.java   Source Code and License 5 votes vote down vote up
public static void closeSilently(ParcelFileDescriptor c) {
	if (c == null)
		return;
	try {
		c.close();
	} catch (Throwable t) {
		Log.w(TAG, "fail to close", t);
	}
}
 
Example 36
Project: YuiHatano   File: ShadowSQLiteSession.java   Source Code and License 5 votes vote down vote up
/**
 * Executes a statement that returns a single BLOB result as a
 * file descriptor to a shared memory region.
 *
 * @param sql                The SQL statement to execute.
 * @param bindArgs           The arguments to bind, or null if none.
 * @param connectionFlags    The connection flags to use if a connection must be
 *                           acquired by this operation.  Refer to {@link SQLiteConnectionPool}.
 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
 * @return The file descriptor for a shared memory region that contains
 * the value of the first column in the first row of the result set as a BLOB,
 * or null if none.
 * @throws SQLiteException            if an error occurs, such as a syntax error
 *                                    or invalid number of bind arguments.
 * @throws OperationCanceledException if the operation was canceled.
 */
public ParcelFileDescriptor executeForBlobFileDescriptor(String sql, Object[] bindArgs,
                                                         int connectionFlags, CancellationSignal cancellationSignal) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    if (executeSpecial(sql, bindArgs, connectionFlags, cancellationSignal)) {
        return null;
    }

    acquireConnection(sql, connectionFlags, cancellationSignal); // might throw
    try {
        return mConnection.executeForBlobFileDescriptor(sql, bindArgs,
                cancellationSignal); // might throw
    } finally {
        releaseConnection(); // might throw
    }
}
 
Example 37
Project: backup   File: ContentProviderRestoreComponent.java   Source Code and License 5 votes vote down vote up
private int transferFullRestoreData(ParcelFileDescriptor outputFileDescriptor) {
    ZipInputStream inputStream = restoreState.getInputStream();
    OutputStream outputStream = new FileOutputStream(outputFileDescriptor.getFileDescriptor());

    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int bytesRead = NO_MORE_DATA;

    try {
        bytesRead = inputStream.read(buffer);

        if (bytesRead <= 0) {
            bytesRead = NO_MORE_DATA;
        } else {
            outputStream.write(buffer, 0, bytesRead);
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception while streaming restore data: ", e);
        return TRANSPORT_ERROR;

    } finally {
        if (bytesRead == NO_MORE_DATA) {

            if (restoreState.getInputFileDescriptor() != null) {
                IoUtils.closeQuietly(restoreState.getInputFileDescriptor());
            }

            restoreState.setInputFileDescriptor(null);
            restoreState.setInputStream(null);
        }

        IoUtils.closeQuietly(outputFileDescriptor);
    }

    return bytesRead;
}
 
Example 38
Project: QuanMinTV   File: IOUtils.java   Source Code and License 5 votes vote down vote up
public static void closeSilently(ParcelFileDescriptor c) {
	if (c == null)
		return;
	try {
		c.close();
	} catch (Throwable t) {
		Log.w(TAG, "fail to close", t);
	}
}
 
Example 39
Project: simple-share-android   File: StorageProvider.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 40
Project: Hotspot-master-devp   File: MediaGalleryActivity.java   Source Code and License 5 votes vote down vote up
private void handleVideo(MediaInfo mVideoInfo) {
        mCurrentVideoInfo = mVideoInfo;
        String assetpath = mVideoInfo.getAssetcover();
        File srcFile = new File(assetpath);
        int dotindex = assetpath.lastIndexOf(".");
        if (dotindex != -1) {
            String type = assetpath.substring(dotindex, assetpath.length());
            String compressPath = mSession.getCompressPath();
            if (Build.VERSION.SDK_INT >= 18) {
                FileOutputStream fos = null;
                try {
                    mCacheVideoPath = compressPath + (compressPath.endsWith(File.separator) ? "" : File.separator) + "savorVideo" + type;
                    Uri uriForFile = FileProvider.getUriForFile(this, "com.savor.savorphone.fileprovider", srcFile);
                    ContentResolver contentResolver = getContentResolver();
                    ParcelFileDescriptor pFileDesCripter = contentResolver.openFileDescriptor(uriForFile, "r");
                    FileDescriptor fileDesCripter = pFileDesCripter.getFileDescriptor();
//                    MediaTranscoder.getInstance().transcodeVideo(fileDesCripter, mCacheVideoPath,
//                            MediaFormatStrategyPresets.createExportPreset960x540Strategy(), listener);
                    future = MediaTranscoder.getInstance().transcodeVideo(fileDesCripter, mCacheVideoPath,
                            MediaFormatStrategyPresets.createAndroid720pStrategy(8000 * 1000, 128 * 1000, 1), listener);
                } catch (Exception e) {
                    e.printStackTrace();
                    handleFileCopy(mVideoInfo, srcFile, type, compressPath);
                }
            } else {
                handleFileCopy(mVideoInfo, srcFile, type, compressPath);
            }
        }
    }