android.os.ParcelFileDescriptor#adoptFd ( )源码实例Demo

下面列出了android.os.ParcelFileDescriptor#adoptFd ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: bcm-android   文件: MemoryFileUtil.java
public static ParcelFileDescriptor getParcelFileDescriptor(MemoryFile file) throws IOException {
    try {
        Method method = MemoryFile.class.getDeclaredMethod("getFileDescriptor");
        FileDescriptor fileDescriptor = (FileDescriptor) method.invoke(file);

        Field field = fileDescriptor.getClass().getDeclaredField("descriptor");
        field.setAccessible(true);

        int fd = field.getInt(fileDescriptor);

        return ParcelFileDescriptor.adoptFd(fd);

    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | NoSuchFieldException e) {
        throw new IOException(e);
    }
}
 
源代码2 项目: android_9.0.0_r45   文件: AppFuseBridge.java
public ParcelFileDescriptor addBridge(MountScope mountScope)
        throws FuseUnavailableMountException, NativeDaemonConnectorException {
    try {
        synchronized (this) {
            Preconditions.checkArgument(mScopes.indexOfKey(mountScope.mountId) < 0);
            if (mNativeLoop == 0) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final int fd = native_add_bridge(
                    mNativeLoop, mountScope.mountId, mountScope.open().detachFd());
            if (fd == -1) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final ParcelFileDescriptor result = ParcelFileDescriptor.adoptFd(fd);
            mScopes.put(mountScope.mountId, mountScope);
            mountScope = null;
            return result;
        }
    } finally {
        IoUtils.closeQuietly(mountScope);
    }
}
 
源代码3 项目: android_9.0.0_r45   文件: TextToSpeechService.java
@Override
public int synthesizeToFileDescriptor(
        IBinder caller,
        CharSequence text,
        ParcelFileDescriptor fileDescriptor,
        Bundle params,
        String utteranceId) {
    if (!checkNonNull(caller, text, fileDescriptor, params)) {
        return TextToSpeech.ERROR;
    }

    // In test env, ParcelFileDescriptor instance may be EXACTLY the same
    // one that is used by client. And it will be closed by a client, thus
    // preventing us from writing anything to it.
    final ParcelFileDescriptor sameFileDescriptor =
            ParcelFileDescriptor.adoptFd(fileDescriptor.detachFd());

    SpeechItem item =
            new SynthesisToFileOutputStreamSpeechItem(
                    caller,
                    Binder.getCallingUid(),
                    Binder.getCallingPid(),
                    params,
                    utteranceId,
                    text,
                    new ParcelFileDescriptor.AutoCloseOutputStream(
                            sameFileDescriptor));
    return mSynthHandler.enqueueSpeechItem(TextToSpeech.QUEUE_ADD, item);
}
 
源代码4 项目: android_9.0.0_r45   文件: SQLiteConnection.java
/**
 * 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 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,
        CancellationSignal cancellationSignal) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    final int cookie = mRecentOperations.beginOperation("executeForBlobFileDescriptor",
            sql, bindArgs);
    try {
        final PreparedStatement statement = acquirePreparedStatement(sql);
        try {
            throwIfStatementForbidden(statement);
            bindArguments(statement, bindArgs);
            applyBlockGuardPolicy(statement);
            attachCancellationSignal(cancellationSignal);
            try {
                int fd = nativeExecuteForBlobFileDescriptor(
                        mConnectionPtr, statement.mStatementPtr);
                return fd >= 0 ? ParcelFileDescriptor.adoptFd(fd) : null;
            } finally {
                detachCancellationSignal(cancellationSignal);
            }
        } finally {
            releasePreparedStatement(statement);
        }
    } catch (RuntimeException ex) {
        mRecentOperations.failOperation(cookie, ex);
        throw ex;
    } finally {
        mRecentOperations.endOperation(cookie);
    }
}
 
源代码5 项目: android_9.0.0_r45   文件: MemoryIntArray.java
@Override
public void writeToParcel(Parcel parcel, int flags) {
    ParcelFileDescriptor pfd = ParcelFileDescriptor.adoptFd(mFd);
    try {
        // Don't let writing to a parcel to close our fd - plz
        parcel.writeParcelable(pfd, flags & ~Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
    } finally {
        pfd.detachFd();
    }
}
 
源代码6 项目: sqlite-android   文件: SQLiteConnection.java
/**
 * 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 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,
        CancellationSignal cancellationSignal) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    final int cookie = mRecentOperations.beginOperation("executeForBlobFileDescriptor",
            sql, bindArgs);
    try {
        final PreparedStatement statement = acquirePreparedStatement(sql);
        try {
            throwIfStatementForbidden(statement);
            bindArguments(statement, bindArgs);
            applyBlockGuardPolicy(statement);
            attachCancellationSignal(cancellationSignal);
            try {
                int fd = nativeExecuteForBlobFileDescriptor(
                        mConnectionPtr, statement.mStatementPtr);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
                    return fd >= 0 ? ParcelFileDescriptor.adoptFd(fd) : null;
                } else {
                    throw new UnsupportedOperationException();
                }
            } finally {
                detachCancellationSignal(cancellationSignal);
            }
        } finally {
            releasePreparedStatement(statement);
        }
    } catch (RuntimeException ex) {
        mRecentOperations.failOperation(cookie, ex);
        throw ex;
    } finally {
        mRecentOperations.endOperation(cookie);
    }
}
 
源代码7 项目: 365browser   文件: PrintingControllerImpl.java
private static void closeFileDescriptor(int fd) {
    if (fd != -1) return;
    ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.adoptFd(fd);
    if (fileDescriptor != null) {
        try {
            fileDescriptor.close();
        } catch (IOException ioe) {
            /* ignore */
        }
    }
}
 
源代码8 项目: 365browser   文件: MediaResourceGetter.java
@VisibleForTesting
void configure(int fd, long offset, long length) {
    ParcelFileDescriptor parcelFd = ParcelFileDescriptor.adoptFd(fd);
    try {
        mRetriever.setDataSource(parcelFd.getFileDescriptor(),
                offset, length);
    } finally {
        try {
            parcelFd.close();
        } catch (IOException e) {
            Log.e(TAG, "Failed to close file descriptor: %s", e);
        }
    }
}
 
源代码9 项目: 365browser   文件: MediaPlayerBridge.java
@CalledByNative
protected boolean setDataSourceFromFd(int fd, long offset, long length) {
    try {
        ParcelFileDescriptor parcelFd = ParcelFileDescriptor.adoptFd(fd);
        getLocalPlayer().setDataSource(parcelFd.getFileDescriptor(), offset, length);
        parcelFd.close();
        return true;
    } catch (IOException e) {
        Log.e(TAG, "Failed to set data source from file descriptor: " + e);
        return false;
    }
}
 
源代码10 项目: squidb   文件: SQLiteConnection.java
/**
 * 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 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,
        CancellationSignal cancellationSignal) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    final int cookie = mRecentOperations.beginOperation("executeForBlobFileDescriptor",
            sql, bindArgs);
    try {
        final PreparedStatement statement = acquirePreparedStatement(sql);
        try {
            throwIfStatementForbidden(statement);
            bindArguments(statement, bindArgs);
            applyBlockGuardPolicy(statement);
            attachCancellationSignal(cancellationSignal);
            try {
                int fd = nativeExecuteForBlobFileDescriptor(
                        mConnectionPtr, statement.mStatementPtr);
                return fd >= 0 ? ParcelFileDescriptor.adoptFd(fd) : null;
            } finally {
                detachCancellationSignal(cancellationSignal);
            }
        } finally {
            releasePreparedStatement(statement);
        }
    } catch (RuntimeException ex) {
        mRecentOperations.failOperation(cookie, ex);
        throw ex;
    } finally {
        mRecentOperations.endOperation(cookie);
    }
}
 
源代码11 项目: mollyim-android   文件: MemoryFileDescriptor.java
/**
 * @param debugName    The name supplied in name is used as a filename and will be displayed
 *                     as the target of the corresponding symbolic link in the directory
 *                     /proc/self/fd/.  The displayed name is always prefixed with memfd:
 *                     and serves only for debugging purposes.  Names do not affect the
 *                     behavior of the file descriptor, and as such multiple files can have
 *                     the same name without any side effects.
 * @param sizeEstimate An estimated upper bound on this file. This is used to check there will be
 *                     enough RAM available and to register with a global counter of reservations.
 *                     Use zero to avoid RAM check.
 * @return MemoryFileDescriptor
 * @throws MemoryLimitException If there is not enough available RAM to comfortably fit this file.
 * @throws MemoryFileCreationException If fails to create a memory file descriptor.
 */
public static MemoryFileDescriptor newMemoryFileDescriptor(@NonNull Context context,
                                                           @NonNull String debugName,
                                                           long sizeEstimate)
    throws MemoryFileException
{
  if (sizeEstimate < 0) throw new IllegalArgumentException();

  if (sizeEstimate > 0) {
    ActivityManager            activityManager = ServiceUtil.getActivityManager(context);
    ActivityManager.MemoryInfo memoryInfo      = new ActivityManager.MemoryInfo();

    synchronized (MemoryFileDescriptor.class) {
      activityManager.getMemoryInfo(memoryInfo);

      long remainingRam = memoryInfo.availMem - memoryInfo.threshold - sizeEstimate - sizeOfAllMemoryFileDescriptors;

      if (remainingRam <= 0) {
        NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
        Log.w(TAG, String.format("Not enough RAM available without taking the system into a low memory state.%n" +
                                 "Available: %s%n" +
                                 "Low memory threshold: %s%n" +
                                 "Requested: %s%n" +
                                 "Total MemoryFileDescriptor limit: %s%n" +
                                 "Shortfall: %s",
        numberFormat.format(memoryInfo.availMem),
        numberFormat.format(memoryInfo.threshold),
        numberFormat.format(sizeEstimate),
        numberFormat.format(sizeOfAllMemoryFileDescriptors),
        numberFormat.format(remainingRam)
        ));
        throw new MemoryLimitException();
      }

      sizeOfAllMemoryFileDescriptors += sizeEstimate;
    }
  }

  int fileDescriptor = FileUtils.createMemoryFileDescriptor(debugName);

  if (fileDescriptor < 0) {
    Log.w(TAG, "Failed to create file descriptor: " + fileDescriptor);
    throw new MemoryFileCreationException();
  }

  return new MemoryFileDescriptor(ParcelFileDescriptor.adoptFd(fileDescriptor), sizeEstimate);
}
 
源代码12 项目: cronet   文件: AndroidNetworkLibrary.java
/**
 * Tag socket referenced by {@code ifd} with {@code tag} for UID {@code uid}.
 *
 * Assumes thread UID tag isn't set upon entry, and ensures thread UID tag isn't set upon exit.
 * Unfortunately there is no TrafficStatis.getThreadStatsUid().
 */
@CalledByNative
private static void tagSocket(int ifd, int uid, int tag) throws IOException {
    // Set thread tags.
    int oldTag = TrafficStats.getThreadStatsTag();
    if (tag != oldTag) {
        TrafficStats.setThreadStatsTag(tag);
    }
    if (uid != TrafficStatsUid.UNSET) {
        ThreadStatsUid.set(uid);
    }

    // Apply thread tags to socket.

    // First, convert integer file descriptor (ifd) to FileDescriptor.
    final ParcelFileDescriptor pfd;
    final FileDescriptor fd;
    // The only supported way to generate a FileDescriptor from an integer file
    // descriptor is via ParcelFileDescriptor.adoptFd(). Unfortunately prior to Android
    // Marshmallow ParcelFileDescriptor.detachFd() didn't actually detach from the
    // FileDescriptor, so use reflection to set {@code fd} into the FileDescriptor for
    // versions prior to Marshmallow. Here's the fix that went into Marshmallow:
    // https://android.googlesource.com/platform/frameworks/base/+/b30ad6f
    if (Build.VERSION.SDK_INT < VERSION_CODES.M) {
        pfd = null;
        fd = SetFileDescriptor.createWithFd(ifd);
    } else {
        pfd = ParcelFileDescriptor.adoptFd(ifd);
        fd = pfd.getFileDescriptor();
    }
    // Second, convert FileDescriptor to Socket.
    Socket s = new SocketFd(fd);
    // Third, tag the Socket.
    TrafficStats.tagSocket(s);
    s.close(); // No-op but always good to close() Closeables.
    // Have ParcelFileDescriptor relinquish ownership of the file descriptor.
    if (pfd != null) {
        pfd.detachFd();
    }

    // Restore prior thread tags.
    if (tag != oldTag) {
        TrafficStats.setThreadStatsTag(oldTag);
    }
    if (uid != TrafficStatsUid.UNSET) {
        ThreadStatsUid.clear();
    }
}