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

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

源代码1 项目: android_9.0.0_r45   文件: ProcessStatsService.java
private void dumpAggregatedStats(PrintWriter pw, long aggregateHours, long now,
        String reqPackage, boolean isCompact, boolean dumpDetails, boolean dumpFullDetails,
        boolean dumpAll, boolean activeOnly) {
    ParcelFileDescriptor pfd = getStatsOverTime(aggregateHours*60*60*1000
            - (ProcessStats.COMMIT_PERIOD/2));
    if (pfd == null) {
        pw.println("Unable to build stats!");
        return;
    }
    ProcessStats stats = new ProcessStats(false);
    InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
    stats.read(stream);
    if (stats.mReadError != null) {
        pw.print("Failure reading: "); pw.println(stats.mReadError);
        return;
    }
    if (isCompact) {
        stats.dumpCheckinLocked(pw, reqPackage);
    } else {
        if (dumpDetails || dumpFullDetails) {
            stats.dumpLocked(pw, reqPackage, now, !dumpFullDetails, dumpAll, activeOnly);
        } else {
            stats.dumpSummaryLocked(pw, reqPackage, now, activeOnly);
        }
    }
}
 
源代码2 项目: kognitivo   文件: VideoUploader.java
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;
    }
}
 
源代码3 项目: 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();
    }
}
 
源代码4 项目: android-test   文件: TestStorage.java
/**
 * Gets the input stream for a given Uri.
 *
 * @param uri The Uri for which the InputStream is required.
 */
InputStream getInputStream(Uri uri) throws FileNotFoundException {
  checkNotNull(uri);

  ContentProviderClient providerClient = null;
  try {
    providerClient = makeContentProviderClient(contentResolver, uri);
    // Assignment to a variable is required. Do not inline.
    ParcelFileDescriptor pfd = providerClient.openFile(uri, "r");
    // Buffered to improve performance.
    return new BufferedInputStream(new ParcelFileDescriptor.AutoCloseInputStream(pfd));
  } 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();
    }
  }
}
 
源代码5 项目: Android-SingleSignOn   文件: AidlNetworkRequest.java
/**
 * The InputStreams needs to be closed after reading from it
 *
 * @param request                {@link NextcloudRequest} request to be executed on server via Files app
 * @param requestBodyInputStream inputstream to be sent to the server
 * @return InputStream answer from server as InputStream
 * @throws Exception or SSOException
 */
public InputStream performNetworkRequest(NextcloudRequest request, InputStream requestBodyInputStream) throws Exception {
    InputStream os = null;
    Exception exception;
    try {
        ParcelFileDescriptor output = performAidlNetworkRequest(request, requestBodyInputStream);
        os = new ParcelFileDescriptor.AutoCloseInputStream(output);
        exception = deserializeObject(os);
    } catch (ClassNotFoundException e) {
        //e.printStackTrace();
        exception = e;
    }

    // Handle Remote Exceptions
    if (exception != null) {
        if (exception.getMessage() != null) {
            exception = parseNextcloudCustomException(exception);
        }
        throw exception;
    }
    return os;
}
 
源代码6 项目: za-Farmer   文件: UiDevice.java
/**
 * Executes a shell command using shell user identity, and return the standard output in string.
 * <p>
 * Calling function with large amount of output will have memory impacts, and the function call
 * will block if the command executed is blocking.
 * <p>Note: calling this function requires API level 21 or above
 * @param cmd the command to run
 * @return the standard output of the command
 * @throws IOException
 * @since API Level 21
 * @hide
 */
public String executeShellCommand(String cmd) throws IOException {
    ParcelFileDescriptor pfd = mInstrumentation.getUiAutomation().executeShellCommand(cmd);
    byte[] buf = new byte[512];
    int bytesRead;
    FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
    StringBuffer stdout = new StringBuffer();
    while ((bytesRead = fis.read(buf)) != -1) {
        stdout.append(new String(buf, 0, bytesRead));
    }
    fis.close();
    return stdout.toString();
}
 
源代码7 项目: android_9.0.0_r45   文件: ProcessStatsService.java
private void dumpAggregatedStats(ProtoOutputStream proto, long fieldId, int aggregateHours, long now) {
    ParcelFileDescriptor pfd = getStatsOverTime(aggregateHours*60*60*1000
            - (ProcessStats.COMMIT_PERIOD/2));
    if (pfd == null) {
        return;
    }
    ProcessStats stats = new ProcessStats(false);
    InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
    stats.read(stream);
    if (stats.mReadError != null) {
        return;
    }
    stats.writeToProto(proto, fieldId, now);
}
 
源代码8 项目: FacebookNewsfeedSample-Android   文件: Request.java
public void writeFile(String key, ParcelFileDescriptor descriptor) throws IOException {
    writeContentDisposition(key, key, "content/unknown");

    ParcelFileDescriptor.AutoCloseInputStream inputStream = null;
    BufferedInputStream bufferedInputStream = null;
    int totalBytes = 0;
    try {
        inputStream = new ParcelFileDescriptor.AutoCloseInputStream(descriptor);
        bufferedInputStream = new BufferedInputStream(inputStream);

        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
            this.outputStream.write(buffer, 0, bytesRead);
            totalBytes += bytesRead;
        }
    } finally {
        if (bufferedInputStream != null) {
            bufferedInputStream.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    writeLine("");
    writeRecordBoundary();
    logger.appendKeyValue("    " + key, String.format("<Data: %d>", totalBytes));
}
 
源代码9 项目: FireFiles   文件: ParcelFileDescriptorUtil.java
@SuppressWarnings("unused")
public static ParcelFileDescriptor pipeTo(OutputStream outputStream)
        throws IOException {
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
    final InputStream input = new ParcelFileDescriptor.AutoCloseInputStream(pipe[0]);

    new TransferThread(input, outputStream).start();

    return pipe[1];
}
 
源代码10 项目: FireFiles   文件: DocumentArchive.java
/**
 * Creates a DocumentsArchive instance for opening, browsing and accessing
 * documents within the archive passed as a file descriptor.
 *
 * <p>Note, that this method should be used only if the document does not exist
 * on the local storage. A snapshot file will be created, which may be slower
 * and consume significant resources, in contrast to using
 * {@see createForLocalFile(Context, File, String, char, Uri}.
 *
 * @param context Context of the provider.
 * @param descriptor File descriptor for the archive's contents.
 * @param documentId ID of the archive document.
 * @param idDelimiter Delimiter for constructing IDs of documents within the archive.
 *            The delimiter must never be used for IDs of other documents.
 * @param Uri notificationUri Uri for notifying that the archive file has changed.
 * @see createForLocalFile(Context, File, String, char, Uri)
 */
public static DocumentArchive createForParcelFileDescriptor(
        Context context, ParcelFileDescriptor descriptor, String documentId,
        char idDelimiter, @Nullable Uri notificationUri)
        throws IOException {
    File snapshotFile = null;
    try {
        // Create a copy of the archive, as ZipFile doesn't operate on streams.
        // Moreover, ZipInputStream would be inefficient for large files on
        // pipes.
        snapshotFile = File.createTempFile("android.support.provider.snapshot{",
                "}.zip", context.getCacheDir());

        try {
            final FileOutputStream outputStream =
                    new ParcelFileDescriptor.AutoCloseOutputStream(
                            ParcelFileDescriptor.open(
                                    snapshotFile, ParcelFileDescriptor.MODE_WRITE_ONLY));
            final ParcelFileDescriptor.AutoCloseInputStream inputStream =
                    new ParcelFileDescriptor.AutoCloseInputStream(descriptor);
            final byte[] buffer = new byte[32 * 1024];
            int bytes;
            while ((bytes = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytes);
            }
            outputStream.flush();
            return new DocumentArchive(context, snapshotFile, documentId, idDelimiter,
                    notificationUri);
        } catch (Exception e){
            Crashlytics.logException(e);
            return null;
        }
    } finally {
        // On UNIX the file will be still available for processes which opened it, even
        // after deleting it. Remove it ASAP, as it won't be used by anyone else.
        if (snapshotFile != null) {
            snapshotFile.delete();
        }
    }
}
 
源代码11 项目: FireFiles   文件: ParcelFileDescriptorUtil.java
@SuppressWarnings("unused")
public static ParcelFileDescriptor pipeTo(OutputStream outputStream)
        throws IOException {
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
    final InputStream input = new ParcelFileDescriptor.AutoCloseInputStream(pipe[0]);

    new TransferThread(input, outputStream).start();

    return pipe[1];
}
 
源代码12 项目: FireFiles   文件: DocumentArchive.java
/**
 * Creates a DocumentsArchive instance for opening, browsing and accessing
 * documents within the archive passed as a file descriptor.
 *
 * <p>Note, that this method should be used only if the document does not exist
 * on the local storage. A snapshot file will be created, which may be slower
 * and consume significant resources, in contrast to using
 * {@see createForLocalFile(Context, File, String, char, Uri}.
 *
 * @param context Context of the provider.
 * @param descriptor File descriptor for the archive's contents.
 * @param documentId ID of the archive document.
 * @param idDelimiter Delimiter for constructing IDs of documents within the archive.
 *            The delimiter must never be used for IDs of other documents.
 * @param Uri notificationUri Uri for notifying that the archive file has changed.
 * @see createForLocalFile(Context, File, String, char, Uri)
 */
public static DocumentArchive createForParcelFileDescriptor(
        Context context, ParcelFileDescriptor descriptor, String documentId,
        char idDelimiter, @Nullable Uri notificationUri)
        throws IOException {
    File snapshotFile = null;
    try {
        // Create a copy of the archive, as ZipFile doesn't operate on streams.
        // Moreover, ZipInputStream would be inefficient for large files on
        // pipes.
        snapshotFile = File.createTempFile("android.support.provider.snapshot{",
                "}.zip", context.getCacheDir());

        try {
            final FileOutputStream outputStream =
                    new ParcelFileDescriptor.AutoCloseOutputStream(
                            ParcelFileDescriptor.open(
                                    snapshotFile, ParcelFileDescriptor.MODE_WRITE_ONLY));
            final ParcelFileDescriptor.AutoCloseInputStream inputStream =
                    new ParcelFileDescriptor.AutoCloseInputStream(descriptor);
            final byte[] buffer = new byte[32 * 1024];
            int bytes;
            while ((bytes = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytes);
            }
            outputStream.flush();
            return new DocumentArchive(context, snapshotFile, documentId, idDelimiter,
                    notificationUri);
        } catch (Exception e){
            Crashlytics.logException(e);
            return null;
        }
    } finally {
        // On UNIX the file will be still available for processes which opened it, even
        // after deleting it. Remove it ASAP, as it won't be used by anyone else.
        if (snapshotFile != null) {
            snapshotFile.delete();
        }
    }
}
 
源代码13 项目: HypFacebook   文件: Request.java
public void writeFile(String key, ParcelFileDescriptor descriptor) throws IOException {
    writeContentDisposition(key, key, "content/unknown");

    ParcelFileDescriptor.AutoCloseInputStream inputStream = null;
    BufferedInputStream bufferedInputStream = null;
    int totalBytes = 0;
    try {
        inputStream = new ParcelFileDescriptor.AutoCloseInputStream(descriptor);
        bufferedInputStream = new BufferedInputStream(inputStream);

        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
            this.outputStream.write(buffer, 0, bytesRead);
            totalBytes += bytesRead;
        }
    } finally {
        if (bufferedInputStream != null) {
            bufferedInputStream.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
    writeLine("");
    writeRecordBoundary();
    logger.appendKeyValue("    " + key, String.format("<Data: %d>", totalBytes));
}
 
private String executeShellCommand(String cmd) throws Exception {
  ParcelFileDescriptor pfd = uiAutomation.executeShellCommand(cmd);
  StringBuilder stdout = new StringBuilder();
  try (FileInputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfd)) {
    byte[] buffer = new byte[1024];
    int bytesRead = 0;

    while ((bytesRead = inputStream.read(buffer)) != -1) {
      stdout.append(new String(buffer, 0, bytesRead, UTF_8));
    }
  }

  Log.i(TAG, "$ adb shell " + cmd + "\n" + stdout);
  return stdout.toString().trim(); // trim trailing newline
}
 
源代码15 项目: android-test   文件: TestFileContentProviderTest.java
private String read(ParcelFileDescriptor fileDescriptor, Charset inputCharset)
    throws IOException {
  BufferedReader reader =
      new BufferedReader(
          new InputStreamReader(
              new ParcelFileDescriptor.AutoCloseInputStream(fileDescriptor), inputCharset));
  return read(reader);
}
 
源代码16 项目: android-test   文件: AtraceLogger.java
/**
 * Method to write data into byte array
 *
 * @param pfDescriptor Used to read the content returned by shell command
 * @param outputStream Write the data to this output stream read from pfDescriptor
 * @throws IOException
 */
private void writeDataToByteStream(
    ParcelFileDescriptor pfDescriptor, ByteArrayOutputStream outputStream) throws IOException {
  InputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfDescriptor);
  try {
    byte[] buffer = new byte[BUFFER_SIZE];
    int length;
    while ((length = inputStream.read(buffer)) >= 0) {
      outputStream.write(buffer, 0, length);
    }
  } finally {
    inputStream.close();
  }
}
 
源代码17 项目: openpgp-api   文件: ParcelFileDescriptorUtil.java
public static TransferThread pipeTo(OutputStream outputStream, ParcelFileDescriptor output)
        throws IOException {

    TransferThread t = new TransferThread(new ParcelFileDescriptor.AutoCloseInputStream(output), outputStream);

    t.start();
    return t;
}
 
源代码18 项目: libstreaming   文件: AudioStream.java
@Override
protected void encodeWithMediaRecorder() throws IOException {
	
	// We need a local socket to forward data output by the camera to the packetizer
	createSockets();

	Log.v(TAG,"Requested audio with "+mQuality.bitRate/1000+"kbps"+" at "+mQuality.samplingRate/1000+"kHz");
	
	mMediaRecorder = new MediaRecorder();
	mMediaRecorder.setAudioSource(mAudioSource);
	mMediaRecorder.setOutputFormat(mOutputFormat);
	mMediaRecorder.setAudioEncoder(mAudioEncoder);
	mMediaRecorder.setAudioChannels(1);
	mMediaRecorder.setAudioSamplingRate(mQuality.samplingRate);
	mMediaRecorder.setAudioEncodingBitRate(mQuality.bitRate);
	
	// We write the output of the camera in a local socket instead of a file !			
	// This one little trick makes streaming feasible quiet simply: data from the camera
	// can then be manipulated at the other end of the socket
	FileDescriptor fd = null;
	if (sPipeApi == PIPE_API_PFD) {
		fd = mParcelWrite.getFileDescriptor();
	} else  {
		fd = mSender.getFileDescriptor();
	}
	mMediaRecorder.setOutputFile(fd);
	mMediaRecorder.setOutputFile(fd);

	mMediaRecorder.prepare();
	mMediaRecorder.start();

	InputStream is = null;
	
	if (sPipeApi == PIPE_API_PFD) {
		is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead);
	} else  {
		try {
			// mReceiver.getInputStream contains the data from the camera
			is = mReceiver.getInputStream();
		} catch (IOException e) {
			stop();
			throw new IOException("Something happened with the local sockets :/ Start failed !");
		}
	}

	// the mPacketizer encapsulates this stream in an RTP stream and send it over the network
	mPacketizer.setInputStream(is);
	mPacketizer.start();
	mStreaming = true;
	
}
 
源代码19 项目: android_9.0.0_r45   文件: AssetFileDescriptor.java
/**
 * Create and return a new auto-close input stream for this asset.  This
 * will either return a full asset {@link AutoCloseInputStream}, or
 * an underlying {@link ParcelFileDescriptor.AutoCloseInputStream
 * ParcelFileDescriptor.AutoCloseInputStream} depending on whether the
 * the object represents a complete file or sub-section of a file.  You
 * should only call this once for a particular asset.
 */
public FileInputStream createInputStream() throws IOException {
    if (mLength < 0) {
        return new ParcelFileDescriptor.AutoCloseInputStream(mFd);
    }
    return new AutoCloseInputStream(this);
}
 
源代码20 项目: JsDroidCmd   文件: UiDevice.java
/**
 * Executes a shell command using shell user identity, and return the
 * standard output in string.
 * <p>
 * Calling function with large amount of output will have memory impacts,
 * and the function call will block if the command executed is blocking.
 * <p>
 * Note: calling this function requires API level 21 or above
 * 
 * @param cmd
 *            the command to run
 * @return the standard output of the command
 * @throws IOException
 * @since API Level 21
 * @hide
 */
public String executeShellCommand(String cmd) throws IOException {
	ParcelFileDescriptor pfd = mUiAutomationBridge.getUiAutomation()
			.executeShellCommand(cmd);
	byte[] buf = new byte[512];
	int bytesRead;
	FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
	StringBuffer stdout = new StringBuffer();
	while ((bytesRead = fis.read(buf)) != -1) {
		stdout.append(new String(buf, 0, bytesRead));
	}
	fis.close();
	return stdout.toString();
}