private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) { Bitmap bm = null; byte[] art = null; String path = null; if (albumid < 0 && songid < 0) { throw new IllegalArgumentException("Must specify an album or a song id"); } try { if (albumid < 0) { Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart"); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if (pfd != null) { FileDescriptor fd = pfd.getFileDescriptor(); bm = BitmapFactory.decodeFileDescriptor(fd); } } else { Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid); ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); if (pfd != null) { FileDescriptor fd = pfd.getFileDescriptor(); bm = BitmapFactory.decodeFileDescriptor(fd); } } } catch (FileNotFoundException ex) { // } return bm; }
/* Return sampled down image for given Uri */ private Bitmap decodeSampledBitmapFromUri(Uri imageUri, int reqWidth, int reqHeight) { Bitmap bitmap; ParcelFileDescriptor parcelFileDescriptor = null; try { parcelFileDescriptor = mActivity.getContentResolver().openFileDescriptor(imageUri, "r"); } catch (FileNotFoundException e) { // TODO handle error e.printStackTrace(); } if (parcelFileDescriptor != null) { FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); // decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); // calculate inSampleSize options.inSampleSize = calculateSampleParameter(options, reqWidth, reqHeight); // decode bitmap with inSampleSize set options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); return bitmap; } else { return null; } }
public static Bitmap getArtwork(Context context, long songId, long albumId, int targetSize) { if (albumId < 0 && songId < 0) { return null; } Bitmap bmp = null; try { ParcelFileDescriptor pfd = null; if (albumId < 0) { Uri uri = Uri.parse("content://media/external/audio/media/" + songId + "/albumart"); pfd = context.getContentResolver().openFileDescriptor(uri, "r"); } else { Uri uri = ContentUris.withAppendedId(AlbumArtUri, albumId); pfd = context.getContentResolver().openFileDescriptor(uri, "r"); } if (pfd == null) { return null; } bmp = decodeImage(pfd.getFileDescriptor(), targetSize); pfd.close(); } catch (Exception e) { e.printStackTrace(); } return bmp; }
public boolean mkdir() throws IOException { if (file.exists()) { return file.isDirectory(); } File tmpFile = new File(file, ".MediaWriteTemp"); int albumId = getTemporaryAlbumId(); if (albumId == 0) { throw new IOException("Fail"); } Uri albumUri = Uri.parse(ALBUM_ART_URI + '/' + albumId); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, tmpFile.getAbsolutePath()); if (contentResolver.update(albumUri, values, null, null) == 0) { values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId); contentResolver.insert(Uri.parse(ALBUM_ART_URI), values); } try { ParcelFileDescriptor fd = contentResolver.openFileDescriptor(albumUri, "r"); fd.close(); } finally { MediaFile tmpMediaFile = new MediaFile(context, tmpFile); tmpMediaFile.delete(); } return file.exists(); }
public boolean loadFromUri(Uri uri) { ParcelFileDescriptor parcelFileDescriptor = null; try { parcelFileDescriptor = Base.activity.getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); copyBitmap(BitmapFactory.decodeFileDescriptor(fileDescriptor)); parcelFileDescriptor.close(); parcelFileDescriptor = null; if (_Source != null) { _BitmapRect = new Rect(0, 0, _Source.getWidth(), _Source.getHeight()); } } catch (FileNotFoundException fnfE) { return false; } catch (IOException ioE) { return false; } catch (Exception e) { return false; } if (parcelFileDescriptor != null) { try { parcelFileDescriptor.close(); } catch (IOException e) { return false; } } return true; }
public static boolean mkdir(final Context context, final File file) throws IOException { if (file.exists()) { return file.isDirectory(); } final File tmpFile = new File(file, ".MediaWriteTemp"); final int albumId = getTemporaryAlbumId(context); if (albumId == 0) { throw new IOException("Failed to create temporary album id."); } final Uri albumUri = Uri.parse(String.format(Locale.US, ALBUM_ART_URI + "/%d", albumId)); final ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, tmpFile.getAbsolutePath()); final ContentResolver contentResolver = context.getContentResolver(); if (contentResolver.update(albumUri, values, null, null) == 0) { values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, albumId); contentResolver.insert(Uri.parse(ALBUM_ART_URI), values); } try { final ParcelFileDescriptor fd = contentResolver.openFileDescriptor(albumUri, "r"); fd.close(); } finally { delete(context, tmpFile); } return file.exists(); }
private void passTcpFileDescriptor( LocalSocket fdSocket, OutputStream outputStream, String socketId, String dstIp, int dstPort, int connectTimeout) throws Exception { Socket sock = new Socket(); sock.setTcpNoDelay(true); // force file descriptor being created if (protect(sock)) { try { sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout); ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock); tcpSockets.put(socketId, sock); fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()}); outputStream.write('*'); outputStream.flush(); fd.detachFd(); } catch (ConnectException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } catch (SocketTimeoutException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } finally { outputStream.flush(); } } else { LogUtils.e("protect tcp socket failed"); } }
@Override public ParcelFileDescriptor openDocument( String documentId, String mode, CancellationSignal signal) throws FileNotFoundException { final File file = getFileForDocId(documentId); final File visibleFile = getFileForDocId(documentId, true); final int pfdMode = ParcelFileDescriptor.parseMode(mode); if (pfdMode == ParcelFileDescriptor.MODE_READ_ONLY || visibleFile == null) { return ParcelFileDescriptor.open(file, pfdMode); } else { try { // When finished writing, kick off media scanner return ParcelFileDescriptor.open( file, pfdMode, mHandler, new OnCloseListener() { @Override public void onClose(IOException e) { final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(visibleFile)); getContext().sendBroadcast(intent); } }); } catch (IOException e) { throw new FileNotFoundException("Failed to open for writing: " + e); } } }
// from Parcelable public LibInfo(Parcel in) { mLoadAddress = in.readLong(); mLoadSize = in.readLong(); mRelroStart = in.readLong(); mRelroSize = in.readLong(); ParcelFileDescriptor fd = in.readFileDescriptor(); mRelroFd = fd.detachFd(); }
@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); } }
private BitmapFactory.Options snifBitmapOptions() { ParcelFileDescriptor input = getPFD(); if (input == null) return null; try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapManager.instance().decodeFileDescriptor(input.getFileDescriptor(), options); return options; } finally { Util.closeSilently(input); } }
@NonNull private ParcelFileDescriptor safeOpenFileHelper(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { Cursor c = query(uri, new String[] {"_data"}, null, null, null); int count = (c != null) ? c.getCount() : 0; if (count != 1) { // If there is not exactly one result, throw an appropriate // exception. if (c != null) { c.close(); } if (count == 0) { throw new FileNotFoundException("No entry for " + uri); } throw new FileNotFoundException("Multiple items at " + uri); } c.moveToFirst(); int i = c.getColumnIndex("_data"); String path = (i >= 0 ? c.getString(i) : null); c.close(); if (path == null) { throw new FileNotFoundException("Column _data not found."); } File filePath = new File(path); try { // The MmsProvider shouldn't open a file that isn't MMS data, so we verify that the // _data path actually points to MMS data. That safeguards ourselves from callers who // inserted or updated a URI (more specifically the _data column) with disallowed paths. // TODO(afurtado): provide a more robust mechanism to avoid disallowed _data paths to // be inserted/updated in the first place, including via SQL injection. if (!filePath .getCanonicalPath() .startsWith(getContext().getDir(PARTS_DIR_NAME, 0).getCanonicalPath())) { Log.e( TAG, "openFile: path " + filePath.getCanonicalPath() + " does not start with " + getContext().getDir(PARTS_DIR_NAME, 0).getCanonicalPath()); // Don't care return value return null; } } catch (IOException e) { Log.e(TAG, "openFile: create path failed " + e, e); return null; } int modeBits = ParcelFileDescriptor.parseMode(mode); return ParcelFileDescriptor.open(filePath, modeBits); }
// Get album art for specified album. This method will not try to // fall back to getting artwork directly from the file, nor will // it attempt to repair the database. private static Bitmap getArtworkQuick(Context context, long album_id, int w, int h) { // NOTE: There is in fact a 1 pixel border on the right side in the ImageView // used to display this drawable. Take it into account now, so we don't have to // scale later. w -= 1; ContentResolver res = context.getContentResolver(); Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id); if (uri != null) { ParcelFileDescriptor fd = null; try { fd = res.openFileDescriptor(uri, "r"); int sampleSize = 1; // Compute the closest power-of-two scale factor // and pass that to sBitmapOptionsCache.inSampleSize, which will // result in faster decoding and better quality sBitmapOptionsCache.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache); int nextWidth = sBitmapOptionsCache.outWidth >> 1; int nextHeight = sBitmapOptionsCache.outHeight >> 1; while (nextWidth > w && nextHeight > h) { sampleSize <<= 1; nextWidth >>= 1; nextHeight >>= 1; } sBitmapOptionsCache.inSampleSize = sampleSize; sBitmapOptionsCache.inJustDecodeBounds = false; Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache); if (b != null) { // finally rescale to exactly the size we need if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) { Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true); // Bitmap.createScaledBitmap() can return the same bitmap if (tmp != b) b.recycle(); b = tmp; } } return b; } catch (FileNotFoundException e) { } finally { try { if (fd != null) fd.close(); } catch (IOException e) { } } } return null; }
public static Bitmap getBitmapFromUri(Uri uri, Context context) throws IOException { ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = null; try { image = BitmapFactory.decodeFileDescriptor(fileDescriptor); } catch (Exception e) { Log.e("BitmapFromUri", e.getMessage()); e.printStackTrace(); } parcelFileDescriptor.close(); return image; }
private void passUdpFileDescriptor( LocalSocket fdSocket, OutputStream outputStream, String socketId) throws Exception { DatagramSocket sock = new DatagramSocket(); if (protect(sock)) { ParcelFileDescriptor fd = ParcelFileDescriptor.fromDatagramSocket(sock); udpSockets.put(socketId, sock); fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()}); outputStream.write('*'); outputStream.flush(); fd.detachFd(); } else { LogUtils.e("protect udp socket failed"); } }
@Override protected Bitmap doInBackground(final Void... pParams) { try { ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver().openFileDescriptor(mUri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; } catch (Exception ex) { return null; } }
/** * Translates Content ID urls (CID urls) into provider queries for the associated attachment. With * the attachment in hand, it's trivial to open a stream to the file containing the content of the * attachment. * * @param uri the raw URI from the HTML document in the Webview * @param message the message containing the HTML that is being rendered * @return a response if a stream to the attachment file can be created from the CID URL; * <tt>null</tt> if it cannot for any reason */ protected final WebResourceResponse loadCIDUri(Uri uri, ConversationMessage message) { // if the url is not a CID url, we do nothing if (!"cid".equals(uri.getScheme())) { return null; } // cid urls can be translated to content urls final String cid = uri.getSchemeSpecificPart(); if (cid == null) { return null; } if (message.attachmentByCidUri == null) { return null; } final Uri queryUri = Uri.withAppendedPath(message.attachmentByCidUri, cid); if (queryUri == null) { return null; } // query for the attachment using its cid final ContentResolver cr = getActivity().getContentResolver(); final Cursor c = cr.query(queryUri, UIProvider.ATTACHMENT_PROJECTION, null, null, null); if (c == null) { return null; } // create the attachment from the cursor, if one was found final Attachment target; try { if (!c.moveToFirst()) { return null; } target = new Attachment(c); } finally { c.close(); } // try to return a response that includes a stream to the attachment data try { final ParcelFileDescriptor fd = cr.openFileDescriptor(target.contentUri, "r"); final InputStream stream = new FileInputStream(fd.getFileDescriptor()); return new WebResourceResponse(target.getContentType(), null, stream); } catch (FileNotFoundException e) { // if no attachment file was found return null to let webview handle it return null; } }
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { switch (code) { case INTERFACE_TRANSACTION: { reply.writeString(DESCRIPTOR); return true; } case TRANSACTION_attachEngine: { data.enforceInterface(DESCRIPTOR); android.service.wallpaper.IWallpaperEngine _arg0; _arg0 = android.service.wallpaper.IWallpaperEngine.Stub.asInterface( data.readStrongBinder()); this.attachEngine(_arg0); reply.writeNoException(); return true; } case TRANSACTION_engineShown: { data.enforceInterface(DESCRIPTOR); android.service.wallpaper.IWallpaperEngine _arg0; _arg0 = android.service.wallpaper.IWallpaperEngine.Stub.asInterface( data.readStrongBinder()); this.engineShown(_arg0); reply.writeNoException(); return true; } case TRANSACTION_setWallpaper: { data.enforceInterface(DESCRIPTOR); java.lang.String _arg0; _arg0 = data.readString(); android.os.ParcelFileDescriptor _result = this.setWallpaper(_arg0); reply.writeNoException(); if ((_result != null)) { reply.writeInt(1); _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE); } else { reply.writeInt(0); } return true; } } return super.onTransact(code, data, reply, flags); }
public Bitmap getMusicImg(String mAlbumArtURI) { File file = new File(mAlbumArtURI); Bitmap bt = null; try { ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); bt = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, null); if (bt == null) { } else { } } catch (FileNotFoundException e) { e.printStackTrace(); } return bt; }
public static boolean isUriValid(Uri uri, ContentResolver resolver) { if (uri == null) return false; try { ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r"); if (pfd == null) { Log.e(TAG, "Fail to open URI. URI=" + uri); return false; } pfd.close(); } catch (IOException ex) { return false; } return true; }
@Override protected void onStop() { super.onStop(); try { if (parcelRead != null) { parcelRead.close(); parcelWrite.close(); } } catch (IOException e) { e.printStackTrace(); } mediaRecorder.stop(); mediaRecorder.release(); camera.release(); }
private void setupDimension() { ParcelFileDescriptor input = null; try { input = mContentResolver.openFileDescriptor(mUri, "r"); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapManager.instance().decodeFileDescriptor(input.getFileDescriptor(), options); mWidth = options.outWidth; mHeight = options.outHeight; } catch (FileNotFoundException ex) { mWidth = 0; mHeight = 0; } finally { Util.closeSilently(input); } }
/** Closes the accessory and cleans up all lose ends */ private void closeAccessory() { if (open == false) { return; } open = false; enabled = false; permissionRequested = false; if (readThread != null) { readThread.cancel(); } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } if (parcelFileDescriptor != null) { try { parcelFileDescriptor.close(); } catch (IOException e) { } } outputStream = null; // readThread = null; parcelFileDescriptor = null; }
@Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { String LOG_TAG = CLASS_NAME + " "; Log.d(LOG_TAG, "Called with uri: '" + uri + "'." + uri.getLastPathSegment()); // Check incoming Uri against the matcher switch (uriMatcher.match(uri)) { // If it returns 1 - then it matches the Uri defined in onCreate case 1: // The desired file name is specified by the last segment of the // path // // Take this and build the path to the file String fileLocation = getContext().getCacheDir() + File.separator + uri.getLastPathSegment(); // Create & return a ParcelFileDescriptor pointing to the file // Note: I don't care what mode they ask for - they're only getting // read only ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY); return pfd; // Otherwise unrecognised Uri default: Log.v(LOG_TAG, "Unsupported uri: '" + uri + "'."); throw new FileNotFoundException("Unsupported uri: " + uri.toString()); } }
// from Parcelable @Override public void writeToParcel(Parcel out, int flags) { if (mRelroFd >= 0) { out.writeLong(mLoadAddress); out.writeLong(mLoadSize); out.writeLong(mRelroStart); out.writeLong(mRelroSize); try { ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd); fd.writeToParcel(out, 0); fd.close(); } catch (java.io.IOException e) { Log.e(TAG, "Cant' write LibInfo file descriptor to parcel", e); } } }
private ParcelFileDescriptor getTempStoreFd() { String fileName = getScrapPath(getContext()); /// M: Code analyze 002, fix bug unknown, If the filename is null,it // should run null @{ if (fileName == null) { return null; } /// @} ParcelFileDescriptor pfd = null; try { File file = new File(fileName); // make sure the path is valid and directories created for this file. File parentFile = file.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { Log.e(TAG, "[TempFileProvider] tempStoreFd: " + parentFile.getPath() + "does not exist!"); return null; } pfd = ParcelFileDescriptor.open( file, ParcelFileDescriptor.MODE_READ_WRITE | android.os.ParcelFileDescriptor.MODE_CREATE); } catch (Exception ex) { Log.e(TAG, "getTempStoreFd: error creating pfd for " + fileName, ex); } return pfd; }
// Provide access to the private file as read only @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { if (!mode.equals("r")) { throw new SecurityException("Only read access is allowed"); } return ParcelFileDescriptor.open(generatePictureFile(uri), ParcelFileDescriptor.MODE_READ_ONLY); }
@Override public synchronized void run() { try { Log.d(TAG, "Starting"); // If anything needs to be obtained using the network, get it now. // This greatly reduces the complexity of seamless handover, which // tries to recreate the tunnel without shutting down everything. // In this mode, all we need to know is the server address. InetSocketAddress server = new InetSocketAddress(serverAddress, Integer.parseInt(serverPort)); // We try to create the tunnel for several times. for (int attempt = 0; attempt < CONNECTION_RETRY_COUNT; ++attempt) { handler.sendEmptyMessage(R.string.connecting); // Reset the counter if we were connected. if (run(server)) { attempt = 0; } // Sleep for a while. This also checks if we got interrupted. Thread.sleep(CONNECTION_WAIT_TIMOUT); } Log.d(TAG, "Giving up"); } catch (InterruptedException e) { Log.e(TAG, "VPN thread interrupted " + e); } finally { try { fileDescriptor.close(); } catch (IOException e) { Log.e(TAG, "FileDescriptor close failed " + e); } fileDescriptor = null; vpnParameters = null; handler.sendEmptyMessage(R.string.disconnected); Log.d(TAG, "Exiting"); } }
private FileOutputStream zznR() { if (zzabc == null) { throw new IllegalStateException("setTempDir() must be called before writing this object to a parcel"); } File file; FileOutputStream fileoutputstream; try { file = File.createTempFile("teleporter", ".tmp", zzabc); } catch (IOException ioexception) { throw new IllegalStateException("Could not create temporary file", ioexception); } try { fileoutputstream = new FileOutputStream(file); zzEo = ParcelFileDescriptor.open(file, 0x10000000); } catch (FileNotFoundException filenotfoundexception) { throw new IllegalStateException("Temporary file is somehow already deleted"); } file.delete(); return fileoutputstream; }
private void closeAccessory() { readTh.interrupt(); try { Thread.sleep(50); } catch (InterruptedException e1) { e1.printStackTrace(); } try { if (mFileDescriptor != null) { mFileDescriptor.close(); } } catch (IOException e) { } try { if (mInputStream != null) { mInputStream.close(); } } catch (IOException e) { } try { if (mOutputStream != null) { mOutputStream.close(); } } catch (IOException e) { } mFileDescriptor = null; mOutputStream = null; mInputStream = null; mAccessory = null; avalible = false; showExitNotification(); }