android.os.ParcelFileDescriptor Java Examples

The following examples show how to use android.os.ParcelFileDescriptor. 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 check out the related API usage on the sidebar.
Example #1
Source File: PackageInstaller.java    From android_9.0.0_r45 with 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 #2
Source File: MemoryFileDescriptor.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #3
Source File: FileSnippet.java    From mobly-bundled-snippets with 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 #4
Source File: NonMediaDocumentsProvider.java    From FireFiles with 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 #5
Source File: FimiMediaPlayer.java    From FimiX8-RE with 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 #6
Source File: CallNotificationSoundProvider.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@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 #7
Source File: PartProvider.java    From mollyim-android with 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 #8
Source File: WorkTimeTrackerBackupAgentHelper.java    From trackworktime with GNU General Public License v3.0 6 votes vote down vote up
@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 #9
Source File: FileProvider.java    From android-recipes-app with 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 #10
Source File: ThemeEditorActivity.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: StorageProvider.java    From FireFiles with 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 #12
Source File: UsbStorageProvider.java    From FireFiles with 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 #13
Source File: MtpTools.java    From xDrip-plus with 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 File: MtpTools.java    From xDrip with 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 #15
Source File: VideoBitmapDecoder.java    From giffun with 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 #16
Source File: TestStorage.java    From android-test with 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 #17
Source File: OurFileProvider.java    From secrecy with 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 #18
Source File: PartProvider.java    From bcm-android with 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 #19
Source File: Linker.java    From 365browser with Apache License 2.0 5 votes vote down vote up
public void close() {
    if (mRelroFd >= 0) {
        try {
            ParcelFileDescriptor.adoptFd(mRelroFd).close();
        } catch (java.io.IOException e) {
            if (DEBUG) {
                Log.e(TAG, "Failed to close fd: " + mRelroFd);
            }
        }
        mRelroFd = -1;
    }
}
 
Example #20
Source File: ChromeBackupAgent.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings(value = {"OS_OPEN_STREAM"}, justification = "Closed by backup system")
@SuppressWarnings("unchecked")
public BackupState(ParcelFileDescriptor parceledState) throws IOException {
    if (parceledState == null) return;
    try {
        FileInputStream instream = new FileInputStream(parceledState.getFileDescriptor());
        ObjectInputStream in = new ObjectInputStream(instream);
        mNames = (ArrayList<String>) in.readObject();
        mValues = (ArrayList<byte[]>) in.readObject();
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: Request.java    From HypFacebook with 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 #22
Source File: UriImage.java    From droidddle with 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 #23
Source File: PackageInstallerSession.java    From container with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ParcelFileDescriptor openRead(String name) throws RemoteException {
    try {
        return openReadInternal(name);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #24
Source File: PrintJobProxy.java    From NewXmPluginSDK with 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 #25
Source File: BarcodeProvider.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: EarthsProvider.java    From earth with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
        throws FileNotFoundException {
    if (!"r".equals(mode)) {
        throw new UnsupportedOperationException();
    }

    final int type = matcher.match(uri);

    if (type != 2 && type != 3) {
        throw new UnsupportedOperationException();
    }

    final Cursor cursor = query(uri, null, null, null, null);

    if (cursor == null) {
        throw new FileNotFoundException();
    }

    final Earth earth = Earth.fromCursor(cursor);

    cursor.close();

    if (earth == null) {
        throw new FileNotFoundException();
    }

    final File file = new File(earth.file);

    if (!file.isFile()) {
        throw new FileNotFoundException();
    }

    return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
 
Example #27
Source File: AppsProvider.java    From FireFiles with 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 #28
Source File: BarcodeProvider.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
@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 #29
Source File: MyTracksBackupAgent.java    From mytracks with Apache License 2.0 5 votes vote down vote up
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
    ParcelFileDescriptor newState) throws IOException {
  Log.i(TAG, "Performing backup");
  SharedPreferences preferences = this.getSharedPreferences(
      Constants.SETTINGS_NAME, Context.MODE_PRIVATE);

  backupPreferences(data, preferences);
  Log.i(TAG, "Backup complete");
}
 
Example #30
Source File: KcaVpnService.java    From kcanotify with 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);
    }
}