Example usage for android.os ParcelFileDescriptor close

List of usage examples for android.os ParcelFileDescriptor close

Introduction

In this page you can find the example usage for android.os ParcelFileDescriptor close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Close the ParcelFileDescriptor.

Usage

From source file:com.android.mail.compose.ComposeActivity.java

private static void closeOpenedAttachmentFds(final SendOrSaveMessage sendOrSaveMessage) {
    final Bundle openedFds = sendOrSaveMessage.attachmentFds();
    if (openedFds != null) {
        final Set<String> keys = openedFds.keySet();
        for (final String key : keys) {
            final ParcelFileDescriptor fd = openedFds.getParcelable(key);
            if (fd != null) {
                try {
                    fd.close();
                } catch (IOException e) {
                    // Do nothing
                }//ww w  .  j  a v a 2s .c o m
            }
        }
    }
}

From source file:android.webkit.cts.WebViewTest.java

public void testPrinting() throws Throwable {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;/*  w ww . j a  va 2s. c  o  m*/
    }
    mOnUiThread.loadDataAndWaitForCompletion("<html><head></head>" + "<body>foo</body></html>", "text/html",
            null);
    final PrintDocumentAdapter adapter = mOnUiThread.createPrintDocumentAdapter();
    printDocumentStart(adapter);
    PrintAttributes attributes = new PrintAttributes.Builder().setMediaSize(PrintAttributes.MediaSize.ISO_A4)
            .setResolution(new PrintAttributes.Resolution("foo", "bar", 300, 300))
            .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();
    final WebViewCtsActivity activity = getActivity();
    final File file = activity.getFileStreamPath(PRINTER_TEST_FILE);
    final ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file,
            ParcelFileDescriptor.parseMode("w"));
    final FutureTask<Boolean> result = new FutureTask<Boolean>(new Callable<Boolean>() {
        public Boolean call() {
            return true;
        }
    });
    printDocumentLayout(adapter, null, attributes, new LayoutResultCallback() {
        // Called on UI thread
        @Override
        public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
            savePrintedPage(adapter, descriptor, result);
        }
    });
    try {
        result.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
        assertTrue(file.length() > 0);
        FileInputStream in = new FileInputStream(file);
        byte[] b = new byte[PDF_PREAMBLE.length()];
        in.read(b);
        String preamble = new String(b);
        assertEquals(PDF_PREAMBLE, preamble);
    } finally {
        // close the descriptor, if not closed already.
        descriptor.close();
        file.delete();
    }
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private void setSize(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, BluetoothMapAppParams ap) {
    if ((ap.getParameterMask() & MASK_SIZE) != 0) {
        int size = 0;
        if (fi.msgType == FilterInfo.TYPE_SMS) {
            String subject = c.getString(c.getColumnIndex(Sms.BODY));
            size = subject.length();//from w ww . j  a  v a2  s.  c  o m
        } else if (fi.msgType == FilterInfo.TYPE_MMS) {
            size = c.getInt(c.getColumnIndex(Mms.MESSAGE_SIZE));
        } else if (fi.msgType == FilterInfo.TYPE_EMAIL) {
            long msgId = Long.valueOf(c.getString(c.getColumnIndex("_id")));
            String textContent, htmlContent;
            Uri uriAddress = Uri.parse("content://com.android.email.provider/body");
            Cursor cr = mResolver.query(uriAddress, Body.CONTENT_PROJECTION, BodyColumns.MESSAGE_KEY + "=?",
                    new String[] { String.valueOf(msgId) }, null);
            if (cr != null && cr.moveToFirst()) {
                ParcelFileDescriptor fd = null;
                String textContentURI = cr.getString(cr.getColumnIndex(BodyColumns.TEXT_CONTENT_URI));
                if (textContentURI != null) {
                    try {
                        Log.v(TAG, " TRY EMAIL BODY textURI " + textContentURI);
                        fd = mResolver.openFileDescriptor(Uri.parse(textContentURI), "r");
                    } catch (FileNotFoundException ex) {
                        if (V)
                            Log.w(TAG, ex);
                    }
                }
                if (fd == null) {
                    String htmlContentURI = cr.getString(cr.getColumnIndex(BodyColumns.HTML_CONTENT_URI));
                    if (htmlContentURI != null) {
                        try {
                            Log.v(TAG, " TRY EMAIL BODY htmlURI " + htmlContentURI);
                            fd = mResolver.openFileDescriptor(Uri.parse(htmlContentURI), "r");
                        } catch (FileNotFoundException ex) {
                            if (V)
                                Log.w(TAG, ex);
                        }
                    }
                }
                if (fd != null) {
                    //Size in bytes
                    size = (Long.valueOf(fd.getStatSize()).intValue());
                    try {
                        fd.close();
                    } catch (IOException ex) {
                        if (V)
                            Log.w(TAG, ex);
                    }

                } else {
                    Log.e(TAG, "MessageSize Email NOT AVAILABLE");
                }
                cr.close();
            }
        }
        if (D)
            Log.d(TAG, "setSize: " + size);
        e.setSize(size);
    }
}

From source file:com.groundupworks.wings.facebook.FacebookEndpoint.java

@Override
public Set<ShareNotification> processShareRequests() {
    Set<ShareNotification> notifications = new HashSet<ShareNotification>();

    // Get params associated with the linked account.
    FacebookSettings settings = fetchSettings();
    if (settings != null) {
        // Get share requests for Facebook.
        int destinationId = settings.getDestinationId();
        Destination destination = new Destination(destinationId, ENDPOINT_ID);
        List<ShareRequest> shareRequests = mDatabase.checkoutShareRequests(destination);
        int shared = 0;
        String intentUri = null;// w w w .j  a  v  a2  s . c  om

        if (!shareRequests.isEmpty()) {
            // Try open session with cached access token.
            Session session = Session.openActiveSessionFromCache(mContext);
            if (session != null && session.isOpened()) {
                // Process share requests.
                for (ShareRequest shareRequest : shareRequests) {
                    File file = new File(shareRequest.getFilePath());
                    ParcelFileDescriptor fileDescriptor = null;
                    try {
                        // Construct graph params.
                        fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
                        Bundle params = new Bundle();
                        params.putParcelable(SHARE_KEY_PICTURE, fileDescriptor);

                        String pageAccessToken = settings.optPageAccessToken();
                        if (DestinationId.PAGE == destinationId && !TextUtils.isEmpty(pageAccessToken)) {
                            params.putString(SHARE_KEY_PAGE_ACCESS_TOKEN, pageAccessToken);
                        }

                        String photoPrivacy = settings.optPhotoPrivacy();
                        if (!TextUtils.isEmpty(photoPrivacy)) {
                            params.putString(SHARE_KEY_PHOTO_PRIVACY, photoPrivacy);
                        }

                        // Execute upload request synchronously. Need to use RequestBatch to set connection timeout.
                        Request request = new Request(session, settings.getAlbumGraphPath(), params,
                                HttpMethod.POST, null);
                        RequestBatch requestBatch = new RequestBatch(request);
                        requestBatch.setTimeout(HTTP_REQUEST_TIMEOUT);
                        List<Response> responses = requestBatch.executeAndWait();
                        if (responses != null && !responses.isEmpty()) {
                            // Process response.
                            Response response = responses.get(0);
                            if (response != null) {
                                FacebookRequestError error = response.getError();
                                if (error == null) {
                                    // Mark as successfully processed.
                                    mDatabase.markSuccessful(shareRequest.getId());

                                    // Parse photo id to construct notification intent uri.
                                    if (intentUri == null) {
                                        String photoId = parsePhotoId(response.getGraphObject());
                                        if (photoId != null && photoId.length() > 0) {
                                            intentUri = SHARE_NOTIFICATION_INTENT_BASE_URI + photoId;
                                        }
                                    }

                                    shared++;
                                } else {
                                    mDatabase.markFailed(shareRequest.getId());

                                    Category category = error.getCategory();
                                    if (Category.AUTHENTICATION_RETRY.equals(category)
                                            || Category.PERMISSION.equals(category)) {
                                        // Update account linking state to unlinked.
                                        unlink();
                                    }
                                }
                            } else {
                                mDatabase.markFailed(shareRequest.getId());
                            }
                        } else {
                            mDatabase.markFailed(shareRequest.getId());
                        }
                    } catch (FacebookException e) {
                        mDatabase.markFailed(shareRequest.getId());
                    } catch (IllegalArgumentException e) {
                        mDatabase.markFailed(shareRequest.getId());
                    } catch (FileNotFoundException e) {
                        mDatabase.markFailed(shareRequest.getId());
                    } catch (Exception e) {
                        // Safety.
                        mDatabase.markFailed(shareRequest.getId());
                    } finally {
                        if (fileDescriptor != null) {
                            try {
                                fileDescriptor.close();
                            } catch (IOException e) {
                                // Do nothing.
                            }
                        }
                    }
                }
            } else {
                // Mark all share requests as failed to process since we failed to open an active session.
                for (ShareRequest shareRequest : shareRequests) {
                    mDatabase.markFailed(shareRequest.getId());
                }
            }
        }

        // Construct and add notification representing share results.
        if (shared > 0) {
            notifications.add(new FacebookShareNotification(mContext, destination.getHash(),
                    settings.getAlbumName(), shared, intentUri));
        }
    }

    return notifications;
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

/**
 * Read out the mms parts and update the bMessage object provided i {@linkplain message}
 * @param id the content provider ID of the message
 * @param message the bMessage object to add the information to
 *//*from w ww.  j  a  va  2 s  .  c o  m*/
private void extractEmailParts(long id, BluetoothMapbMessageMmsEmail message) {
    if (V)
        Log.v(TAG, "extractEmailParts with id " + id);
    String emailBody = "";
    Uri uriAddress = Uri.parse("content://com.android.email.provider/body");
    BluetoothMapbMessageMmsEmail.MimePart part;
    Cursor c = null;
    try {
        c = mResolver.query(uriAddress, Body.CONTENT_PROJECTION, BodyColumns.MESSAGE_KEY + "=?",
                new String[] { String.valueOf(id) }, null);
    } catch (Exception e) {

        Log.w(TAG, " EMAIL BODY QUERY FAILDED " + e);
    }
    if (c != null) {
        if (V)
            Log.v(TAG, "cursor not null");
        if (c.moveToFirst()) {
            String textContentURI = c.getString(c.getColumnIndex(BodyColumns.TEXT_CONTENT_URI));
            String htmlContentURI = c.getString(c.getColumnIndex(BodyColumns.HTML_CONTENT_URI));
            if (textContentURI != null || htmlContentURI != null) {
                if (V) {
                    Log.v(TAG, " EMAIL BODY textURI " + textContentURI);
                    Log.v(TAG, " EMAIL BODY htmlURI " + htmlContentURI);
                }
                // GET FD to parse text or HTML content
                ParcelFileDescriptor fd = null;
                if (textContentURI != null) {
                    try {
                        Log.v(TAG, " TRY EMAIL BODY textURI " + textContentURI);
                        fd = mResolver.openFileDescriptor(Uri.parse(textContentURI), "r");
                    } catch (FileNotFoundException e) {
                        if (V)
                            Log.w(TAG, e);
                    }
                }
                if (fd == null) {
                    if (htmlContentURI != null) {
                        //Try HTML content if  TEXT CONTENT NULL
                        try {
                            Log.v(TAG, " TRY EMAIL BODY htmlURI " + htmlContentURI);
                            fd = mResolver.openFileDescriptor(Uri.parse(htmlContentURI), "r");
                        } catch (FileNotFoundException e) {
                            if (V)
                                Log.w(TAG, e);
                        } catch (NullPointerException e) {
                            if (V)
                                Log.w(TAG, e);
                        }
                        String msgBody = null;
                        if (fd != null) {
                            msgBody = readEmailBodyForMessageFd(fd);
                        } else {
                            Log.w(TAG, " FETCH Email BODY File HTML URI FAILED");
                        }
                        if (msgBody != null) {
                            msgBody = msgBody.replaceAll("(?s)(<title>)(.*?)(</title>)", "");
                            msgBody = msgBody.replaceAll("(?s)(<style type=\"text/css\".*?>)(.*?)(</style>)",
                                    "");
                            CharSequence msgText = Html.fromHtml(msgBody);
                            emailBody = msgText.toString();
                            emailBody = emailBody.replaceAll("(?s)(<!--)(.*?)(-->)", "");
                            // Solves problem with Porche Car-kit and Gmails.
                            // Changes unix style line conclusion to DOS style
                            emailBody = emailBody.replaceAll("(?s)(\\r)", "");
                            emailBody = emailBody.replaceAll("(?s)(\\n)", "\r\n");
                        }
                    } else {
                        Log.w(TAG, " FETCH Email BODY File HTML URI FAILED");
                    }
                } else {
                    emailBody = readEmailBodyForMessageFd(fd);
                }
                //Set BMessage emailBody
                message.setEmailBody(emailBody);
                //Parts
                Long partId = c.getLong(c.getColumnIndex(BaseColumns._ID));
                String contentType = "Content-Type: text/plain; charset=\"UTF-8\"";
                String name = null;//c.getString(c.getColumnIndex("displayName"));
                String text = null;

                if (D)
                    Log.d(TAG, "     _id : " + partId + "\n     ct : " + contentType + "\n     partname : "
                            + name);

                part = message.addMimePart();
                part.contentType = contentType;
                part.partName = name;

                try {
                    if (emailBody != null) {
                        part.data = emailBody.getBytes("UTF-8");
                        part.charsetName = "utf-8";
                    }
                } catch (NumberFormatException e) {
                    Log.d(TAG, "extractEmailParts", e);
                    part.data = null;
                    part.charsetName = null;
                } catch (UnsupportedEncodingException e) {
                    Log.d(TAG, "extractEmailParts", e);
                    part.data = null;
                    part.charsetName = null;
                } finally {
                }
                try {
                    if (fd != null)
                        fd.close();
                } catch (IOException e) {
                }
            } else {
                Log.w(TAG, " FETCH Email BODY File URI FAILED");
            }
        }
        c.close();
    }
    message.updateCharset();
    message.setEncoding("8BIT");
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/** Save a .txt file of various test results. */
void saveReport(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    FileOutputStream outputStream;
    try {/*from  www  .j a  v  a  2 s  .c o m*/
        parcelFileDescriptor = getApplicationContext().getContentResolver().openFileDescriptor(uri, "w");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        outputStream = new FileOutputStream(fileDescriptor);

        log("Done creating output stream");

        String endline = "\n";
        final int stringLength = 300;
        StringBuilder sb = new StringBuilder(stringLength);
        sb.append("DateTime = " + mCurrentTime + endline);
        sb.append(INTENT_SAMPLING_FREQUENCY + " = " + getApp().getSamplingRate() + endline);
        sb.append(INTENT_RECORDER_BUFFER + " = "
                + getApp().getRecorderBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_PLAYER_BUFFER + " = "
                + getApp().getPlayerBufferSizeInBytes() / Constant.BYTES_PER_FRAME + endline);
        sb.append(INTENT_AUDIO_THREAD + " = " + getApp().getAudioThreadType() + endline);
        int micSource = getApp().getMicSource();

        String audioType = "unknown";
        switch (getApp().getAudioThreadType()) {
        case Constant.AUDIO_THREAD_TYPE_JAVA:
            audioType = "JAVA";
            break;
        case Constant.AUDIO_THREAD_TYPE_NATIVE:
            audioType = "NATIVE";
            break;
        }
        sb.append(INTENT_AUDIO_THREAD + "_String = " + audioType + endline);

        sb.append(INTENT_MIC_SOURCE + " = " + micSource + endline);
        sb.append(INTENT_MIC_SOURCE + "_String = " + getApp().getMicSourceString(micSource) + endline);
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        sb.append(INTENT_AUDIO_LEVEL + " = " + currentVolume + endline);

        switch (mTestType) {
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_LATENCY:
            if (mCorrelation.mEstimatedLatencyMs > 0.0001) {
                sb.append(String.format("LatencyMs = %.2f", mCorrelation.mEstimatedLatencyMs) + endline);
            } else {
                sb.append(String.format("LatencyMs = unknown") + endline);
            }

            sb.append(String.format("LatencyConfidence = %.2f", mCorrelation.mEstimatedLatencyConfidence)
                    + endline);
            break;
        case Constant.LOOPBACK_PLUG_AUDIO_THREAD_TEST_TYPE_BUFFER_PERIOD:
            sb.append("Buffer Test Duration (s) = " + mBufferTestDuration + endline);

            // report expected recorder buffer period
            int expectedRecorderBufferPeriod = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            sb.append("Expected Recorder Buffer Period (ms) = " + expectedRecorderBufferPeriod + endline);

            // report recorder results
            int recorderBufferSize = mRecorderBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] recorderBufferData = null;
            int recorderBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                recorderBufferData = mRecorderBufferPeriod.getBufferPeriodArray();
                recorderBufferDataMax = mRecorderBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                recorderBufferData = mNativeRecorderBufferPeriodArray;
                recorderBufferDataMax = mNativeRecorderMaxBufferPeriod;
                break;
            }
            if (recorderBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(recorderBufferDataMax + 1, recorderBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(recorderBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(recorderBufferSize,
                        mSamplingRate, usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Recorder Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Recorder Benchmark = " + benchmark + endline);
                sb.append("Recorder Number of Outliers = " + outliers + endline);
            } else {
                sb.append("Cannot Find Recorder Buffer Period Data!" + endline);
            }

            // report player results
            int playerBufferSize = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME;
            int[] playerBufferData = null;
            int playerBufferDataMax = 0;
            switch (mAudioThreadType) {
            case Constant.AUDIO_THREAD_TYPE_JAVA:
                playerBufferData = mPlayerBufferPeriod.getBufferPeriodArray();
                playerBufferDataMax = mPlayerBufferPeriod.getMaxBufferPeriod();
                break;
            case Constant.AUDIO_THREAD_TYPE_NATIVE:
                playerBufferData = mNativePlayerBufferPeriodArray;
                playerBufferDataMax = mNativePlayerMaxBufferPeriod;
                break;
            }
            if (playerBufferData != null) {
                // this is the range of data that actually has values
                int usefulDataRange = Math.min(playerBufferDataMax + 1, playerBufferData.length);
                int[] usefulBufferData = Arrays.copyOfRange(playerBufferData, 0, usefulDataRange);
                PerformanceMeasurement measurement = new PerformanceMeasurement(playerBufferSize, mSamplingRate,
                        usefulBufferData);
                boolean isBufferSizesMismatch = measurement.determineIsBufferSizesMatch();
                double benchmark = measurement.computeWeightedBenchmark();
                int outliers = measurement.countOutliers();
                sb.append("Player Buffer Sizes Mismatch = " + isBufferSizesMismatch + endline);
                sb.append("Player Benchmark = " + benchmark + endline);
                sb.append("Player Number of Outliers = " + outliers + endline);

            } else {
                sb.append("Cannot Find Player Buffer Period Data!" + endline);
            }

            // report expected player buffer period
            int expectedPlayerBufferPeriod = mPlayerBufferSizeInBytes / Constant.BYTES_PER_FRAME
                    * Constant.MILLIS_PER_SECOND / mSamplingRate;
            if (audioType.equals("JAVA")) {
                // javaPlayerMultiple depends on the samples written per AudioTrack.write()
                int javaPlayerMultiple = 2;
                expectedPlayerBufferPeriod *= javaPlayerMultiple;
            }
            sb.append("Expected Player Buffer Period (ms) = " + expectedPlayerBufferPeriod + endline);

            // report estimated number of glitches
            int numberOfGlitches = estimateNumberOfGlitches(mGlitchesData);
            sb.append("Estimated Number of Glitches = " + numberOfGlitches + endline);

            // report if the total glitching interval is too long
            sb.append("Total glitching interval too long: " + mGlitchingIntervalTooLong + endline);
        }

        String info = getApp().getSystemInfo();
        sb.append("SystemInfo = " + info + endline);

        outputStream.write(sb.toString().getBytes());
        parcelFileDescriptor.close();
    } catch (Exception e) {
        log("Failed to open text file " + e);
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("Error closing ParcelFile Descriptor");
        }
    }

}