Java Code Examples for android.os.ParcelFileDescriptor

The following examples show how to use android.os.ParcelFileDescriptor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@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);
}
 
Example 2
Source Project: mollyim-android   Source File: PartProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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.");
}
 
Example 3
/**
 * 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;
}
 
Example 4
Source Project: FimiX8-RE   Source File: FimiMediaPlayer.java    License: MIT License 6 votes vote down vote up
@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();
    }
}
 
Example 5
Source Project: android_9.0.0_r45   Source File: PackageInstaller.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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");
        }
    }
}
 
Example 6
@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);
}
 
Example 7
Source Project: FireFiles   Source File: UsbStorageProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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());
        }
    }
 
Example 8
Source Project: xDrip-plus   Source File: MtpTools.java    License: GNU General Public License v3.0 6 votes vote down vote up
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();

}
 
Example 9
Source Project: giffun   Source File: VideoBitmapDecoder.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 10
Source Project: android-test   Source File: TestStorage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
  }
}
 
Example 11
Source Project: bcm-android   Source File: PartProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 12
Source Project: secrecy   Source File: OurFileProvider.java    License: Apache License 2.0 6 votes vote down vote up
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 13
Source Project: xDrip   Source File: MtpTools.java    License: GNU General Public License v3.0 6 votes vote down vote up
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();

}
 
Example 14
Source Project: FireFiles   Source File: StorageProvider.java    License: Apache License 2.0 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 15
Source Project: android-recipes-app   Source File: FileProvider.java    License: Apache License 2.0 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 16
@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());
	}
}
 
Example 17
Source Project: mobly-bundled-snippets   Source File: FileSnippet.java    License: Apache License 2.0 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 18
Source Project: FireFiles   Source File: NonMediaDocumentsProvider.java    License: Apache License 2.0 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 19
public WriteFileAsyncTask(ParcelFileDescriptor destination,
        CancellationSignal cancellationSignal, WriteResultCallback callback) {
    mDestination = destination;
    mResultCallback = callback;
    mCancellationSignal = cancellationSignal;
    mCancellationSignal.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel() {
            cancel(true);
        }
    });
}
 
Example 20
Source Project: Effects-Pro   Source File: LocalStorageProvider.java    License: MIT License 5 votes vote down vote up
@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);
	}
}
 
Example 21
Source Project: FireFiles   Source File: ParcelFileDescriptorUtil.java    License: Apache License 2.0 5 votes vote down vote up
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];
}
 
Example 22
Source Project: APDE   Source File: FileSelection.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example 23
Source Project: Dashchan   Source File: FileProvider.java    License: Apache License 2.0 5 votes vote down vote up
@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();
		}
	}
}
 
Example 24
Source Project: FireFiles   Source File: DocumentArchiveHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 25
Source Project: libcommon   Source File: MediaAVRecorder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * コンストラクタ
 * @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");
}
 
Example 26
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;
            }
        }
    };
}
 
Example 27
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);
}
 
Example 28
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;
}
 
Example 29
Source Project: secrecy   Source File: ObserveFileJob.java    License: Apache License 2.0 5 votes vote down vote up
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
    }
}
 
Example 30
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!");
}
 
Example 31
Source Project: kcanotify   Source File: KcaVpnService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void stopNative(ParcelFileDescriptor vpn, boolean clear) {
    Log.i(TAG, "Stop native clear=" + clear);
    try {
        jni_stop(vpn.getFd(), clear);
    } catch (Throwable ex) {
        // File descriptor might be closed
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        jni_stop(-1, clear);
    }
}
 
Example 32
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal) throws FileNotFoundException {
    Log.d(Config.LOGTAG, "opening file with uri (normal): " + uri.toString());
    String path = uri.getPath();
    if (path != null && path.endsWith(".png") && path.length() >= 5) {
        String jid = path.substring(1).substring(0, path.length() - 4);
        Log.d(Config.LOGTAG, "account:" + jid);
        if (connectAndWait()) {
            Log.d(Config.LOGTAG, "connected to background service");
            try {
                Account account = mXmppConnectionService.findAccountByJid(Jid.of(jid));
                if (account != null) {
                    String shareableUri = account.getShareableUri();
                    String hash = CryptoHelper.getFingerprint(shareableUri);
                    File file = new File(getContext().getCacheDir().getAbsolutePath() + "/barcodes/" + hash);
                    if (!file.exists()) {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                        Bitmap bitmap = create2dBarcodeBitmap(account.getShareableUri(), 1024);
                        OutputStream outputStream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                        outputStream.close();
                        outputStream.flush();
                    }
                    return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
                }
            } catch (Exception e) {
                throw new FileNotFoundException();
            }
        }
    }
    throw new FileNotFoundException();
}
 
Example 33
Source Project: FireFiles   Source File: AppsProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    // Delegate to real provider
    final long token = Binder.clearCallingIdentity();
    try {
        //final long id = Long.parseLong(docId);
        //final ContentResolver resolver = getContext().getContentResolver();
        return null;//resolver.openFileDescriptor(mDm.getUriForDownloadedFile(id), mode);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example 34
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal) throws FileNotFoundException {
	Log.d(Config.LOGTAG, "opening file with uri (normal): " + uri.toString());
	String path = uri.getPath();
	if (path != null && path.endsWith(".png") && path.length() >= 5) {
		String jid = path.substring(1).substring(0, path.length() - 4);
		Log.d(Config.LOGTAG, "account:" + jid);
		if (connectAndWait()) {
			Log.d(Config.LOGTAG, "connected to background service");
			try {
				Account account = mXmppConnectionService.findAccountByJid(Jid.of(jid));
				if (account != null) {
					String shareableUri = account.getShareableUri();
					String hash = CryptoHelper.getFingerprint(shareableUri);
					File file = new File(getContext().getCacheDir().getAbsolutePath() + "/barcodes/" + hash);
					if (!file.exists()) {
						file.getParentFile().mkdirs();
						file.createNewFile();
						Bitmap bitmap = create2dBarcodeBitmap(account.getShareableUri(), 1024);
						OutputStream outputStream = new FileOutputStream(file);
						bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
						outputStream.close();
						outputStream.flush();
					}
					return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
				}
			} catch (Exception e) {
				throw new FileNotFoundException();
			}
		}
	}
	throw new FileNotFoundException();
}
 
Example 35
Source Project: NewXmPluginSDK   Source File: PrintJobProxy.java    License: Apache License 2.0 5 votes vote down vote up
public ParcelFileDescriptor getDocumentData() {
    PrintDocument document = printJob.getDocument();
    if (document == null) {
        return null;
    } else {
        return document.getData();
    }
}
 
Example 36
Source Project: droidddle   Source File: UriImage.java    License: Apache License 2.0 5 votes vote down vote up
private ParcelFileDescriptor getPFD() {
    try {
        if (mUri.getScheme().equals("file")) {
            String path = mUri.getPath();
            return ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY);
        } else {
            return mContentResolver.openFileDescriptor(mUri, "r");
        }
    } catch (FileNotFoundException ex) {
        return null;
    }
}
 
Example 37
Source Project: HypFacebook   Source File: Request.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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));
}
 
Example 38
Source Project: FireFiles   Source File: DownloadStorageProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ParcelFileDescriptor openDocument(String docId, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    // Delegate to real provider
    final long token = Binder.clearCallingIdentity();
    try {
        final long id = Long.parseLong(docId);
        final ContentResolver resolver = getContext().getContentResolver();
        return resolver.openFileDescriptor(mDm.getUriForDownloadedFile(id), mode);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example 39
Source Project: reader   Source File: Util.java    License: MIT License 5 votes vote down vote up
public static void closeSilently(ParcelFileDescriptor c) {
    if (c == null) return;
    try {
        c.close();
    } catch (Throwable t) {
        // do nothing
    }
}
 
Example 40
Source Project: AndroidComponentPlugin   Source File: ActivityThread.java    License: Apache License 2.0 5 votes vote down vote up
public void dumpActivity(FileDescriptor fd, IBinder activitytoken,
        String prefix, String[] args) {
    DumpComponentInfo data = new DumpComponentInfo();
    try {
        data.fd = ParcelFileDescriptor.dup(fd);
        data.token = activitytoken;
        data.prefix = prefix;
        data.args = args;
        queueOrSendMessage(H.DUMP_ACTIVITY, data);
    } catch (IOException e) {
        Slog.w(TAG, "dumpActivity failed", e);
    }
}