Java Code Examples for android.os.ParcelFileDescriptor#close()

The following examples show how to use android.os.ParcelFileDescriptor#close() . 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: AbstractReadOnlyProviderTest.java    From cwac-provider with Apache License 2.0 6 votes vote down vote up
@Test
public void testCannotWrite() throws IOException {
  for (Uri root : ROOTS) {
    Uri source=getStreamSource(root);

    try {
      ParcelFileDescriptor pfd=
        InstrumentationRegistry
          .getContext()
          .getContentResolver()
          .openFileDescriptor(source, "rw");
      pfd.close();
      Assert.fail("expected exception, did not get one");
    }
    catch (FileNotFoundException e) {
      if (!e.getMessage().equals("Not a whole file") &&
        !e.getMessage().equals("Invalid mode for read-only content")) {
        throw e;
      }
    }
  }
}
 
Example 2
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 3
Source File: UsbManager.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Opens the device so it can be used to send and receive
 * data using {@link android.hardware.usb.UsbRequest}.
 *
 * @param device the device to open
 * @return a {@link UsbDeviceConnection}, or {@code null} if open failed
 */
@RequiresFeature(PackageManager.FEATURE_USB_HOST)
public UsbDeviceConnection openDevice(UsbDevice device) {
    try {
        String deviceName = device.getDeviceName();
        ParcelFileDescriptor pfd = mService.openDevice(deviceName, mContext.getPackageName());
        if (pfd != null) {
            UsbDeviceConnection connection = new UsbDeviceConnection(device);
            boolean result = connection.open(deviceName, pfd, mContext);
            pfd.close();
            if (result) {
                return connection;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "exception in UsbManager.openDevice", e);
    }
    return null;
}
 
Example 4
Source File: IOUtils.java    From MyHearts with Apache License 2.0 5 votes vote down vote up
public static void closeSilently(ParcelFileDescriptor c) {
	if (c == null)
		return;
	try {
		c.close();
	} catch (Throwable t) {
		Log.w(TAG, "fail to close", t);
	}
}
 
Example 5
Source File: FileSelection.java    From APDE with GNU General Public License v2.0 5 votes vote down vote up
public static void closeFd(@Nullable ParcelFileDescriptor fd) {
	try {
		if (fd != null) {
			fd.close();
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 6
Source File: CameraProxyActivity.java    From Shelter with Do What The F*ck You Want To Public License 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == REQUEST_OPEN_IMAGE && resultCode == RESULT_OK && data != null) {
        // The image is now opened. We should now read the data and send it to the other Uri
        Uri imageUri = data.getData();
        try {
            ParcelFileDescriptor fd = getContentResolver().openFileDescriptor(imageUri, "r");
            // Thumbnail is required by the definition of ACTION_CAPTURE_IMAGE
            Bitmap thumbnail = Utility.decodeSampledBitmap(fd.getFileDescriptor(), 128, 128);

            if (mOutputUri != null) {
                // The calling app may or may not request for the full image
                // If requested, we write the image, in JPEG format, to the provided URI
                // Note that JPEG is required by the interface.
                Bitmap bmp = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
                OutputStream out = getContentResolver().openOutputStream(mOutputUri);

                // Re-compress the image to another JPEG image through the output URI
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            }

            fd.close();
            Intent resultIntent = new Intent();
            resultIntent.putExtra("data", thumbnail);
            setResult(RESULT_OK, resultIntent);
            finish();
            return;
        } catch (IOException e) {
            // Just silently fail
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }

    // We exit the activity anyway
    setResult(RESULT_CANCELED); // If we succeeded, we should have returned earlier
    finish();
}
 
Example 7
Source File: TranscoderActivity.java    From android-transcoder with Apache License 2.0 5 votes vote down vote up
private void onTranscodeFinished(boolean isSuccess, String toastMessage, ParcelFileDescriptor parcelFileDescriptor) {
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    progressBar.setIndeterminate(false);
    progressBar.setProgress(isSuccess ? PROGRESS_BAR_MAX : 0);
    switchButtonEnabled(false);
    Toast.makeText(TranscoderActivity.this, toastMessage, Toast.LENGTH_LONG).show();
    try {
        parcelFileDescriptor.close();
    } catch (IOException e) {
        Log.w("Error while closing", e);
    }
}
 
Example 8
Source File: MediaAVRecorder.java    From libcommon with 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 9
Source File: FileBackend.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private Bitmap renderPdfDocument(ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
    final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
    final PdfRenderer.Page page = pdfRenderer.openPage(0);
    final Dimensions dimensions = scalePdfDimensions(new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
    final Bitmap rendered = Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
    rendered.eraseColor(0xffffffff);
    page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    page.close();
    pdfRenderer.close();
    fileDescriptor.close();
    return rendered;
}
 
Example 10
Source File: OpenVpnManagementThread.java    From Cybernet-VPN with GNU General Public License v3.0 5 votes vote down vote up
private boolean sendTunFD(String needed, String extra) {
    if (!extra.equals("tun")) {
        // We only support tun
        VpnStatus.logError(String.format("Device type %s requested, but only tun is possible with the Android API, sorry!", extra));
        return false;
    }
    ParcelFileDescriptor pfd = mOpenVPNService.openTun();
    if (pfd == null) return false;
    Method setInt;
    int fdint = pfd.getFd();
    try {
        setInt = FileDescriptor.class.getDeclaredMethod("setInt$", int.class);
        FileDescriptor fdtosend = new FileDescriptor();
        setInt.invoke(fdtosend, fdint);
        FileDescriptor[] fds = {fdtosend};
        mSocket.setFileDescriptorsForSend(fds);
        // Trigger a send so we can close the fd on our side of the channel
        // The API documentation fails to mention that it will not reset the file descriptor to
        // be send and will happily send the file descriptor on every write ...
        String cmd = String.format("needok '%s' %s\n", needed, "ok");
        managmentCommand(cmd);
        // Set the FileDescriptor to null to stop this mad behavior
        mSocket.setFileDescriptorsForSend(null);
        pfd.close();
        return true;
    } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException |
            IOException | IllegalAccessException exp) {
        VpnStatus.logException("Could not send fd over socket", exp);
    }
    return false;
}
 
Example 11
Source File: KcaVpnService.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
private void stopVPN(ParcelFileDescriptor pfd) {
    Log.i(TAG, "Stopping");
    try {
        pfd.close();
    } catch (IOException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}
 
Example 12
Source File: Utils.java    From TurboLauncher with Apache License 2.0 5 votes vote down vote up
public static void closeSilently(ParcelFileDescriptor fd) {
    try {
        if (fd != null) fd.close();
    } catch (Throwable t) {
        Log.w(TAG, "fail to close", t);
    }
}
 
Example 13
Source File: Utils.java    From medialibrary with Apache License 2.0 5 votes vote down vote up
public static void closeSilently(ParcelFileDescriptor fd) {
    try {
        if (fd != null) fd.close();
    } catch (Throwable t) {
        Log.w(TAG, "fail to close", t);
    }
}
 
Example 14
Source File: ExternalOpenVPNService.java    From android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean protectSocket(ParcelFileDescriptor pfd) throws RemoteException {
    checkOpenVPNPermission();
    try {
        boolean success = mService.protect(pfd.getFd());
        pfd.close();
        return success;
    } catch (IOException e) {
        throw new RemoteException(e.getMessage());
    }
}
 
Example 15
Source File: ThreadedRenderer.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void requestBuffer() {
    try {
        final String pkg = mAppContext.getApplicationInfo().packageName;
        ParcelFileDescriptor pfd = mGraphicsStatsService
                .requestBufferForProcess(pkg, mGraphicsStatsCallback);
        nSetProcessStatsBuffer(pfd.getFd());
        pfd.close();
    } catch (Throwable t) {
        Log.w(LOG_TAG, "Could not acquire gfx stats buffer", t);
    }
}
 
Example 16
Source File: Util.java    From reader with 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 17
Source File: Utils.java    From WayHoo with Apache License 2.0 5 votes vote down vote up
public static void closeSilently(ParcelFileDescriptor fd) {
	try {
		if (fd != null)
			fd.close();
	} catch (Throwable t) {
		Log.w(TAG, "fail to close", Log.APP);
	}
}
 
Example 18
Source File: StorageController.java    From slide with MIT License 5 votes vote down vote up
@Override
protected Boolean doInBackground(Void... params) {
    PdfDocument document = new PdfDocument();
    ParcelFileDescriptor pfd = null;
    try {
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(640, 640 * 9 / 16, 1).create();

        for (Slide slide : store.getState().slides()) {
            PdfDocument.Page page = document.startPage(pageInfo);
            page.getCanvas().drawColor(Style.COLOR_SCHEMES[store.getState().colorScheme()][1]);
            slide.render(mContext,
                    page.getCanvas(),
                    page.getCanvas().getWidth(), page.getCanvas().getHeight(),
                    Style.SLIDE_FONT,
                    Style.COLOR_SCHEMES[App.getState().colorScheme()][0],
                    Style.COLOR_SCHEMES[App.getState().colorScheme()][1],
                    true);
            document.finishPage(page);
        }

        pfd = mContext.getContentResolver().openFileDescriptor(uri, "w");
        if (pfd != null) {
            FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
            document.writeTo(fos);
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        document.close();
        if (pfd != null) {
            try { pfd.close(); } catch (IOException ignored) {}
        }
    }
}
 
Example 19
Source File: BlackHoleService.java    From Android-Firewall with GNU General Public License v3.0 5 votes vote down vote up
private void vpnStop(ParcelFileDescriptor pfd) {
    Log.i(TAG, "Stopping");
    try {
        pfd.close();
    } catch (IOException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}
 
Example 20
Source File: OpenVpnManagementThread.java    From EasyVPN-Free with GNU General Public License v3.0 4 votes vote down vote up
private boolean sendTunFD(String needed, String extra) {
    if (!extra.equals("tun")) {
        // We only support tun
        VpnStatus.logError(String.format("Device type %s requested, but only tun is possible with the Android API, sorry!", extra));

        return false;
    }
    ParcelFileDescriptor pfd = mOpenVPNService.openTun();
    if (pfd == null)
        return false;

    Method setInt;
    int fdint = pfd.getFd();
    try {
        setInt = FileDescriptor.class.getDeclaredMethod("setInt$", int.class);
        FileDescriptor fdtosend = new FileDescriptor();

        setInt.invoke(fdtosend, fdint);

        FileDescriptor[] fds = {fdtosend};
        mSocket.setFileDescriptorsForSend(fds);

        // Trigger a send so we can close the fd on our side of the channel
        // The API documentation fails to mention that it will not reset the file descriptor to
        // be send and will happily send the file descriptor on every write ...
        String cmd = String.format("needok '%s' %s\n", needed, "ok");
        managmentCommand(cmd);

        // Set the FileDescriptor to null to stop this mad behavior
        mSocket.setFileDescriptorsForSend(null);

        pfd.close();

        return true;
    } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException |
            IOException | IllegalAccessException exp) {
        VpnStatus.logException("Could not send fd over socket", exp);
    }

    return false;
}