Example usage for android.support.v4.provider DocumentFile getName

List of usage examples for android.support.v4.provider DocumentFile getName

Introduction

In this page you can find the example usage for android.support.v4.provider DocumentFile getName.

Prototype

public abstract String getName();

Source Link

Usage

From source file:com.osama.cryptofm.tasks.EncryptTask.java

private void encryptDocumentFile(DocumentFile file) throws FileNotFoundException {
    Log.d(TAG, "encryptDocumentFile: encrypting document file");
    if (file.isDirectory()) {
        rootDocumentFile = file;/*from ww w. j  ava  2s  .  c om*/
        for (DocumentFile f : file.listFiles()) {
            encryptDocumentFile(f);
        }
    } else {
        //check if root document is not null
        if (rootDocumentFile == null) {
            String path = mFilePaths.get(0).substring(0, mFilePaths.get(0).lastIndexOf('/'));

            Log.d(TAG, "encryptDocumentFile: Getting the root document: " + path);
            rootDocumentFile = FileDocumentUtils.getDocumentFile(new File(path));
        }
        DocumentFile temp = rootDocumentFile.createFile("pgp", file.getName() + ".pgp");
        mCreatedDocumentFiles.add(temp);
        publishProgress(file.getName(), "" + ((FileUtils.getReadableSize((file.length())))));

        InputStream in = CryptoFM.getContext().getContentResolver().openInputStream(file.getUri());
        OutputStream out = CryptoFM.getContext().getContentResolver().openOutputStream(temp.getUri());
        DocumentFileEncryption.encryptFile(in, out, pubKeyFile, true, new Date(file.lastModified()),
                file.getName());

    }
}

From source file:de.arcus.playmusiclib.PlayMusicManager.java

/**
 * Exports a track to the sd card//from  w w w .j  av a  2  s.  co m
 * @param musicTrack The music track you want to export
 * @param uri The document tree
 * @return Returns whether the export was successful
 */
public boolean exportMusicTrack(MusicTrack musicTrack, Uri uri, String path) {

    // Check for null
    if (musicTrack == null)
        return false;

    String srcFile = musicTrack.getSourceFile();

    // Could not find the source file
    if (srcFile == null)
        return false;

    String fileTmp = getTempPath() + "/tmp.mp3";

    // Copy to temp path failed
    if (!SuperUserTools.fileCopy(srcFile, fileTmp))
        return false;

    // Encrypt the file
    if (musicTrack.isEncoded()) {
        String fileTmpCrypt = getTempPath() + "/crypt.mp3";

        // Encrypts the file
        if (trackEncrypt(musicTrack, fileTmp, fileTmpCrypt)) {
            // Remove the old tmp file
            FileTools.fileDelete(fileTmp);

            // New tmp file
            fileTmp = fileTmpCrypt;
        } else {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "Encrypting failed! Continue with decrypted file.");
        }
    }

    String dest;
    Uri copyUri = null;
    if (uri.toString().startsWith("file://")) {
        // Build the full path
        dest = uri.buildUpon().appendPath(path).build().getPath();

        String parentDirectory = new File(dest).getParent();
        FileTools.directoryCreate(parentDirectory);
    } else {
        // Complex uri (Lollipop)
        dest = getTempPath() + "/final.mp3";

        // The root
        DocumentFile document = DocumentFile.fromTreeUri(mContext, uri);

        // Creates the subdirectories
        String[] directories = path.split("\\/");
        for (int i = 0; i < directories.length - 1; i++) {
            String directoryName = directories[i];
            boolean found = false;

            // Search all sub elements
            for (DocumentFile subDocument : document.listFiles()) {
                // Directory exists
                if (subDocument.isDirectory() && subDocument.getName().equals(directoryName)) {
                    document = subDocument;
                    found = true;
                    break;
                }
            }

            if (!found) {
                // Create the directory
                document = document.createDirectory(directoryName);
            }
        }

        // Gets the filename
        String filename = directories[directories.length - 1];

        for (DocumentFile subDocument : document.listFiles()) {
            // Directory exists
            if (subDocument.isFile() && subDocument.getName().equals(filename)) {
                // Delete the file
                subDocument.delete();
                break;
            }
        }

        // Create the mp3 file
        document = document.createFile("music/mp3", filename);

        // Create the directories
        copyUri = document.getUri();
    }

    // We want to export the ID3 tags
    if (mID3Enable) {
        // Adds the meta data
        if (!trackWriteID3(musicTrack, fileTmp, dest)) {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "ID3 writer failed! Continue without ID3 tags.");

            // Failed, moving without meta data
            if (!FileTools.fileMove(fileTmp, dest)) {
                Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

                // Could not copy the file
                return false;
            }
        }
    } else {
        // Moving the file
        if (!FileTools.fileMove(fileTmp, dest)) {
            Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

            // Could not copy the file
            return false;
        }
    }

    // We need to copy the file to a uri
    if (copyUri != null) {
        // Lollipop only
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                // Gets the file descriptor
                ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver()
                        .openFileDescriptor(copyUri, "w");

                // Gets the output stream
                FileOutputStream fileOutputStream = new FileOutputStream(
                        parcelFileDescriptor.getFileDescriptor());

                // Gets the input stream
                FileInputStream fileInputStream = new FileInputStream(dest);

                // Copy the stream
                FileTools.fileCopy(fileInputStream, fileOutputStream);

                // Close all streams
                fileOutputStream.close();
                fileInputStream.close();
                parcelFileDescriptor.close();

            } catch (FileNotFoundException e) {
                Logger.getInstance().logError("ExportMusicTrack", "File not found!");

                // Could not copy the file
                return false;
            } catch (IOException e) {
                Logger.getInstance().logError("ExportMusicTrack",
                        "Failed to write the document: " + e.toString());

                // Could not copy the file
                return false;
            }
        }
    }

    // Delete temp files
    cleanUp();

    // Adds the file to the media system
    //new MediaScanner(mContext, dest);

    // Done
    return true;
}

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

/**
 * Appends mp4 audio/video from {@code anotherFileDescriptor} to
 * {@code mainFileDescriptor}.//from www . j  a v  a2  s . com
 */
public static DocumentFile appendNew(DocumentFile[] inputFiles) {
    try {
        DocumentFile targetFile = inputFiles[0];
        int[] inputFilesFds = new int[inputFiles.length];
        ArrayList<ParcelFileDescriptor> pfdsList = new ArrayList<ParcelFileDescriptor>();

        int i = 0;
        for (DocumentFile f : inputFiles) {
            ParcelFileDescriptor pfd = ApplicationScreen.instance.getContentResolver()
                    .openFileDescriptor(f.getUri(), "rw");
            pfdsList.add(pfd);
            inputFilesFds[i] = pfd.getFd();
            i++;
        }

        if (targetFile.exists() && targetFile.length() > 0) {
            String tmpFileName = targetFile.getName() + ".tmp";
            DocumentFile tmpTargetFile = targetFile.getParentFile().createFile("video/mp4", tmpFileName);
            ParcelFileDescriptor targetFilePfd = ApplicationScreen.instance.getContentResolver()
                    .openFileDescriptor(tmpTargetFile.getUri(), "rw");

            Mp4Editor.appendFds(inputFilesFds, targetFilePfd.getFd());

            targetFilePfd.close();
            for (ParcelFileDescriptor pfd : pfdsList) {
                pfd.close();
            }

            return tmpTargetFile;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

protected void doExportVideo() {
    boolean onPause = this.onPause;
    this.onPause = false;
    boolean isDro = this.modeDRO();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && (documentFileSaved != null || !isDro)) {
        DocumentFile fileSaved = VideoCapturePlugin.documentFileSaved;
        ArrayList<DocumentFile> filesListToExport = documentFilesList;
        String resultName = fileSaved.getName();
        DocumentFile resultFile = fileSaved;

        if (filesListToExport.size() > 0) {
            int inputFileCount = filesListToExport.size();
            if (!onPause)
                inputFileCount++;//from www. j  a  va2  s .c om

            DocumentFile[] inputFiles = new DocumentFile[inputFileCount];

            for (int i = 0; i < filesListToExport.size(); i++) {
                inputFiles[i] = filesListToExport.get(i);
            }

            // If video recording hadn't been paused before STOP was
            // pressed, then last recorded file is not in the list with
            // other files, added to list of files manually.
            if (!onPause) {
                inputFiles[inputFileCount - 1] = fileSaved;
            }

            resultFile = appendNew(inputFiles);

            // Remove merged files, except first one, because it stores the
            // result of merge.
            for (int i = 0; i < filesListToExport.size(); i++) {
                DocumentFile currentFile = filesListToExport.get(i);
                currentFile.delete();
            }

            // If video recording hadn't been paused before STOP was
            // pressed, then last recorded file is not in the list with
            // other files, and should be deleted manually.
            if (!onPause)
                fileSaved.delete();

            String tmpName = resultFile.getName();
            if (resultFile.renameTo(resultName))
                ;

            // Make sure, that there won't be duplicate broken file
            // in phone memory at gallery.
            String args[] = { tmpName };
            ApplicationScreen.instance.getContentResolver().delete(Video.Media.EXTERNAL_CONTENT_URI,
                    Video.Media.DISPLAY_NAME + "=?", args);
        }

        String name = resultFile.getName();
        String data = null;
        // If we able to get File object, than get path from it. Gallery
        // doesn't show the file, if it's stored at phone memory and
        // we need insert new file to gallery manually.
        File file = Util.getFileFromDocumentFile(resultFile);
        if (file != null) {
            data = file.getAbsolutePath();
        } else {
            // This case should typically happen for files saved to SD
            // card.
            data = Util.getAbsolutePathFromDocumentFile(resultFile);
        }

        if (data != null) {
            values.put(VideoColumns.DISPLAY_NAME, name);
            values.put(VideoColumns.DATA, data);
            Uri uri = ApplicationScreen.instance.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
                    values);
            ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
        }
    } else {
        File fileSaved = VideoCapturePlugin.fileSaved;
        ArrayList<File> filesListToExport = filesList;

        File firstFile = fileSaved;

        if (filesListToExport.size() > 0) {
            firstFile = filesListToExport.get(0);

            int inputFileCount = filesListToExport.size();
            if (!onPause)
                inputFileCount++;

            File[] inputFiles = new File[inputFileCount];

            for (int i = 0; i < filesListToExport.size(); i++) {
                inputFiles[i] = filesListToExport.get(i);
            }

            if (!onPause)
                inputFiles[inputFileCount - 1] = fileSaved;

            File resultFile = append(inputFiles);

            for (int i = 0; i < filesListToExport.size(); i++) {
                File currentFile = filesListToExport.get(i);
                currentFile.delete();
            }

            if (resultFile != null) {
                if (!resultFile.getAbsoluteFile().equals(fileSaved.getAbsoluteFile())) {
                    fileSaved.delete();
                    resultFile.renameTo(fileSaved);
                }
            }
        }

        filesListToExport.clear();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && isDro) {
            DocumentFile outputFile = getOutputMediaDocumentFile();
            File file = Util.getFileFromDocumentFile(outputFile);

            if (file != null) {
                // Don't do anything with ouputFile. It's useless, remove
                // it.
                outputFile.delete();
                Uri uri = ApplicationScreen.instance.getContentResolver()
                        .insert(Video.Media.EXTERNAL_CONTENT_URI, values);
                ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
            } else {
                // Copy result file from phone memory to selected folder at
                // SD-card.
                InputStream is = null;
                int len;
                byte[] buf = new byte[4096];
                try {
                    OutputStream os = ApplicationScreen.instance.getContentResolver()
                            .openOutputStream(outputFile.getUri());
                    is = new FileInputStream(firstFile);
                    while ((len = is.read(buf)) > 0) {
                        os.write(buf, 0, len);
                    }
                    is.close();
                    os.close();
                    firstFile.delete();

                    // Make sure, that there won't be duplicate broken file
                    // in phone memory at gallery.
                    String args[] = { firstFile.getAbsolutePath() };
                    ApplicationScreen.instance.getContentResolver().delete(Video.Media.EXTERNAL_CONTENT_URI,
                            Video.Media.DATA + "=?", args);

                    String data = Util.getAbsolutePathFromDocumentFile(outputFile);
                    if (data != null) {
                        values.put(VideoColumns.DATA, data);
                        Uri uri = ApplicationScreen.instance.getContentResolver()
                                .insert(Video.Media.EXTERNAL_CONTENT_URI, values);
                        ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            Uri uri = ApplicationScreen.instance.getContentResolver().insert(Video.Media.EXTERNAL_CONTENT_URI,
                    values);
            ApplicationScreen.getMainContext().sendBroadcast(new Intent(ACTION_NEW_VIDEO, uri));
        }
    }

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);

}

From source file:com.almalence.opencam.PluginManagerBase.java

private void saveInputFileNew(boolean isYUV, Long SessionID, int i, byte[] buffer, int yuvBuffer,
        String fileFormat) {/* www . j  a v a2  s  .c o  m*/

    int mImageWidth = Integer.parseInt(PluginManager.getInstance().getFromSharedMem("imageWidth" + SessionID));
    int mImageHeight = Integer
            .parseInt(PluginManager.getInstance().getFromSharedMem("imageHeight" + SessionID));
    ContentValues values = null;
    String resultOrientation = getFromSharedMem("frameorientation" + (i + 1) + Long.toString(SessionID));
    if (resultOrientation == null) {
        resultOrientation = getFromSharedMem("frameorientation" + i + Long.toString(SessionID));
    }

    String resultMirrored = getFromSharedMem("framemirrored" + (i + 1) + Long.toString(SessionID));
    if (resultMirrored == null) {
        resultMirrored = getFromSharedMem("framemirrored" + i + Long.toString(SessionID));
    }

    Boolean cameraMirrored = false;
    if (resultMirrored != null)
        cameraMirrored = Boolean.parseBoolean(resultMirrored);

    int mDisplayOrientation = 0;
    if (resultOrientation != null) {
        mDisplayOrientation = Integer.parseInt(resultOrientation);
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());
    boolean saveGeoInfo = prefs.getBoolean("useGeoTaggingPrefExport", false);

    DocumentFile file;
    DocumentFile saveDir = getSaveDirNew(false);
    if (saveDir == null || !saveDir.exists()) {
        return;
    }

    file = saveDir.createFile("image/jpeg", fileFormat);
    if (file == null || !file.canWrite()) {
        return;
    }

    OutputStream os = null;
    File bufFile = new File(ApplicationScreen.instance.getFilesDir(), "buffer.jpeg");
    try {
        os = new FileOutputStream(bufFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (os != null) {
        try {
            if (!isYUV) {
                os.write(buffer);
            } else {
                jpegQuality = Integer.parseInt(prefs.getString(MainScreen.sJPEGQualityPref, "95"));

                com.almalence.YuvImage image = new com.almalence.YuvImage(yuvBuffer, ImageFormat.NV21,
                        mImageWidth, mImageHeight, null);
                // to avoid problems with SKIA
                int cropHeight = image.getHeight() - image.getHeight() % 16;
                image.compressToJpeg(new Rect(0, 0, image.getWidth(), cropHeight), jpegQuality, os);
            }
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        mDisplayOrientation = saveExifToInput(bufFile, mDisplayOrientation, cameraMirrored, saveGeoInfo);

        // Copy buffer image with exif tags into result file.
        InputStream is = null;
        int len;
        byte[] buf = new byte[1024];
        try {
            os = ApplicationScreen.instance.getContentResolver().openOutputStream(file.getUri());
            is = new FileInputStream(bufFile);
            while ((len = is.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            is.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    bufFile.delete();

    values = new ContentValues();
    values.put(ImageColumns.TITLE, file.getName().substring(0, file.getName().lastIndexOf(".")));
    values.put(ImageColumns.DISPLAY_NAME, file.getName());
    values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
    values.put(ImageColumns.MIME_TYPE, "image/jpeg");
    values.put(ImageColumns.ORIENTATION, mDisplayOrientation);

    String filePath = file.getName();
    // If we able to get File object, than get path from it.
    // fileObject should not be null for files on phone memory.
    File fileObject = Util.getFileFromDocumentFile(file);
    if (fileObject != null) {
        filePath = fileObject.getAbsolutePath();
        values.put(ImageColumns.DATA, filePath);
    } else {
        // This case should typically happen for files saved to SD
        // card.
        String documentPath = Util.getAbsolutePathFromDocumentFile(file);
        values.put(ImageColumns.DATA, documentPath);
    }

    if (saveGeoInfo) {
        Location l = MLocation.getLocation(ApplicationScreen.getMainContext());
        if (l != null) {
            values.put(ImageColumns.LATITUDE, l.getLatitude());
            values.put(ImageColumns.LONGITUDE, l.getLongitude());
        }
    }

    ApplicationScreen.instance.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}

From source file:org.kde.kdeconnect.Plugins.SharePlugin.SharePlugin.java

@Override
public boolean onPackageReceived(NetworkPackage np) {

    try {/*from w ww  . j av  a  2 s . c  o m*/
        if (np.hasPayload()) {

            Log.i("SharePlugin", "hasPayload");

            final InputStream input = np.getPayload();
            final long fileLength = np.getPayloadSize();
            final String originalFilename = np.getString("filename", Long.toString(System.currentTimeMillis()));

            //We need to check for already existing files only when storing in the default path.
            //User-defined paths use the new Storage Access Framework that already handles this.
            final boolean customDestination = ShareSettingsActivity.isCustomDestinationEnabled(context);
            final String defaultPath = ShareSettingsActivity.getDefaultDestinationDirectory().getAbsolutePath();
            final String filename = customDestination ? originalFilename
                    : FilesHelper.findNonExistingNameForNewFile(defaultPath, originalFilename);

            String displayName = FilesHelper.getFileNameWithoutExt(filename);
            final String mimeType = FilesHelper.getMimeTypeFromFile(filename);

            if ("*/*".equals(mimeType)) {
                displayName = filename;
            }

            final DocumentFile destinationFolderDocument = ShareSettingsActivity
                    .getDestinationDirectory(context);
            final DocumentFile destinationDocument = destinationFolderDocument.createFile(mimeType,
                    displayName);
            final OutputStream destinationOutput = context.getContentResolver()
                    .openOutputStream(destinationDocument.getUri());
            final Uri destinationUri = destinationDocument.getUri();

            final int notificationId = (int) System.currentTimeMillis();
            Resources res = context.getResources();
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setContentTitle(res.getString(R.string.incoming_file_title, device.getName()))
                    .setContentText(res.getString(R.string.incoming_file_text, filename))
                    .setTicker(res.getString(R.string.incoming_file_title, device.getName()))
                    .setSmallIcon(android.R.drawable.stat_sys_download).setAutoCancel(true).setOngoing(true)
                    .setProgress(100, 0, true);

            final NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean successful = true;
                    try {
                        byte data[] = new byte[1024];
                        long progress = 0, prevProgressPercentage = 0;
                        int count;
                        while ((count = input.read(data)) >= 0) {
                            progress += count;
                            destinationOutput.write(data, 0, count);
                            if (fileLength > 0) {
                                if (progress >= fileLength)
                                    break;
                                long progressPercentage = (progress * 100 / fileLength);
                                if (progressPercentage != prevProgressPercentage) {
                                    prevProgressPercentage = progressPercentage;
                                    builder.setProgress(100, (int) progressPercentage, false);
                                    NotificationHelper.notifyCompat(notificationManager, notificationId,
                                            builder.build());
                                }
                            }
                            //else Log.e("SharePlugin", "Infinite loop? :D");
                        }

                        destinationOutput.flush();

                    } catch (Exception e) {
                        successful = false;
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    } finally {
                        try {
                            destinationOutput.close();
                        } catch (Exception e) {
                        }
                        try {
                            input.close();
                        } catch (Exception e) {
                        }
                    }

                    try {
                        Log.i("SharePlugin", "Transfer finished: " + destinationUri.getPath());

                        //Update the notification and allow to open the file from it
                        Resources res = context.getResources();
                        String message = successful
                                ? res.getString(R.string.received_file_title, device.getName())
                                : res.getString(R.string.received_file_fail_title, device.getName());
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                                .setContentTitle(message).setTicker(message)
                                .setSmallIcon(android.R.drawable.stat_sys_download_done).setAutoCancel(true);
                        if (successful) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(destinationUri, mimeType);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                            stackBuilder.addNextIntent(intent);
                            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                                    PendingIntent.FLAG_UPDATE_CURRENT);
                            builder.setContentText(
                                    res.getString(R.string.received_file_text, destinationDocument.getName()))
                                    .setContentIntent(resultPendingIntent);
                        }
                        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                        if (prefs.getBoolean("share_notification_preference", true)) {
                            builder.setDefaults(Notification.DEFAULT_ALL);
                        }
                        NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());

                        if (successful) {
                            if (!customDestination && Build.VERSION.SDK_INT >= 12) {
                                Log.i("SharePlugin", "Adding to downloads");
                                DownloadManager manager = (DownloadManager) context
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                manager.addCompletedDownload(destinationUri.getLastPathSegment(),
                                        device.getName(), true, mimeType, destinationUri.getPath(), fileLength,
                                        false);
                            } else {
                                //Make sure it is added to the Android Gallery anyway
                                MediaStoreHelper.indexFile(context, destinationUri);
                            }
                        }

                    } catch (Exception e) {
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    }
                }
            }).start();

        } else if (np.has("text")) {
            Log.i("SharePlugin", "hasText");

            String text = np.getString("text");
            if (Build.VERSION.SDK_INT >= 11) {
                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(text);
            } else {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            }
            Toast.makeText(context, R.string.shareplugin_text_saved, Toast.LENGTH_LONG).show();
        } else if (np.has("url")) {

            String url = np.getString("url");

            Log.i("SharePlugin", "hasUrl: " + url);

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (openUrlsDirectly) {
                context.startActivity(browserIntent);
            } else {
                Resources res = context.getResources();
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addNextIntent(browserIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                Notification noti = new NotificationCompat.Builder(context)
                        .setContentTitle(res.getString(R.string.received_url_title, device.getName()))
                        .setContentText(res.getString(R.string.received_url_text, url))
                        .setContentIntent(resultPendingIntent)
                        .setTicker(res.getString(R.string.received_url_title, device.getName()))
                        .setSmallIcon(R.drawable.ic_notification).setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_ALL).build();

                NotificationManager notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationHelper.notifyCompat(notificationManager, (int) System.currentTimeMillis(), noti);
            }
        } else {
            Log.e("SharePlugin", "Error: Nothing attached!");
        }

    } catch (Exception e) {
        Log.e("SharePlugin", "Exception");
        e.printStackTrace();
    }

    return true;
}

From source file:com.almalence.opencam.SavingService.java

public void saveResultPictureNew(long sessionID) {
    if (ApplicationScreen.getForceFilename() != null) {
        saveResultPicture(sessionID);/*from  ww w. j a  v  a 2  s .  com*/
        return;
    }

    initSavingPrefs();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // save fused result
    try {
        DocumentFile saveDir = getSaveDirNew(false);

        int imagesAmount = Integer
                .parseInt(getFromSharedMem("amountofresultframes" + Long.toString(sessionID)));

        if (imagesAmount == 0)
            imagesAmount = 1;

        int imageIndex = 0;
        String sImageIndex = getFromSharedMem("resultframeindex" + Long.toString(sessionID));
        if (sImageIndex != null)
            imageIndex = Integer.parseInt(getFromSharedMem("resultframeindex" + Long.toString(sessionID)));

        if (imageIndex != 0)
            imagesAmount = 1;

        ContentValues values = null;

        boolean hasDNGResult = false;
        for (int i = 1; i <= imagesAmount; i++) {
            hasDNGResult = false;
            String format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));

            if (format != null && format.equalsIgnoreCase("dng"))
                hasDNGResult = true;

            String idx = "";

            if (imagesAmount != 1)
                idx += "_" + ((format != null && !format.equalsIgnoreCase("dng") && hasDNGResult)
                        ? i - imagesAmount / 2
                        : i);

            String modeName = getFromSharedMem("modeSaveName" + Long.toString(sessionID));

            // define file name format. from settings!
            String fileFormat = getExportFileName(modeName);
            fileFormat += idx;

            DocumentFile file = null;
            if (ApplicationScreen.getForceFilename() == null) {
                if (hasDNGResult) {
                    file = saveDir.createFile("image/x-adobe-dng", fileFormat + ".dng");
                } else {
                    file = saveDir.createFile("image/jpeg", fileFormat);
                }
            } else {
                file = DocumentFile.fromFile(ApplicationScreen.getForceFilename());
            }

            // Create buffer image to deal with exif tags.
            OutputStream os = null;
            File bufFile = new File(getApplicationContext().getFilesDir(), "buffer.jpeg");
            try {
                os = new FileOutputStream(bufFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Take only one result frame from several results
            // Used for PreShot plugin that may decide which result to save
            if (imagesAmount == 1 && imageIndex != 0) {
                i = imageIndex;
                //With changed frame index we have to get appropriate frame format
                format = getFromSharedMem("resultframeformat" + i + Long.toString(sessionID));
            }

            String resultOrientation = getFromSharedMem(
                    "resultframeorientation" + i + Long.toString(sessionID));
            int orientation = 0;
            if (resultOrientation != null)
                orientation = Integer.parseInt(resultOrientation);

            String resultMirrored = getFromSharedMem("resultframemirrored" + i + Long.toString(sessionID));
            Boolean cameraMirrored = false;
            if (resultMirrored != null)
                cameraMirrored = Boolean.parseBoolean(resultMirrored);

            int x = Integer.parseInt(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            int y = Integer.parseInt(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
            if (orientation == 0 || orientation == 180 || (format != null && format.equalsIgnoreCase("dng"))) {
                x = Integer.valueOf(getFromSharedMem("saveImageWidth" + Long.toString(sessionID)));
                y = Integer.valueOf(getFromSharedMem("saveImageHeight" + Long.toString(sessionID)));
            }

            Boolean writeOrientationTag = true;
            String writeOrientTag = getFromSharedMem("writeorientationtag" + Long.toString(sessionID));
            if (writeOrientTag != null)
                writeOrientationTag = Boolean.parseBoolean(writeOrientTag);

            if (format != null && format.equalsIgnoreCase("jpeg")) {// if result in jpeg format

                if (os != null) {
                    byte[] frame = SwapHeap.SwapFromHeap(
                            Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID))),
                            Integer.parseInt(
                                    getFromSharedMem("resultframelen" + i + Long.toString(sessionID))));
                    os.write(frame);
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (format != null && format.equalsIgnoreCase("dng")
                    && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                saveDNGPicture(i, sessionID, os, x, y, orientation, cameraMirrored);
            } else {// if result in nv21 format
                int yuv = Integer.parseInt(getFromSharedMem("resultframe" + i + Long.toString(sessionID)));
                com.almalence.YuvImage out = new com.almalence.YuvImage(yuv, ImageFormat.NV21, x, y, null);
                Rect r;

                String res = getFromSharedMem("resultfromshared" + Long.toString(sessionID));
                if ((null == res) || "".equals(res) || "true".equals(res)) {
                    // to avoid problems with SKIA
                    int cropHeight = out.getHeight() - out.getHeight() % 16;
                    r = new Rect(0, 0, out.getWidth(), cropHeight);
                } else {
                    if (null == getFromSharedMem("resultcrop0" + Long.toString(sessionID))) {
                        // to avoid problems with SKIA
                        int cropHeight = out.getHeight() - out.getHeight() % 16;
                        r = new Rect(0, 0, out.getWidth(), cropHeight);
                    } else {
                        int crop0 = Integer
                                .parseInt(getFromSharedMem("resultcrop0" + Long.toString(sessionID)));
                        int crop1 = Integer
                                .parseInt(getFromSharedMem("resultcrop1" + Long.toString(sessionID)));
                        int crop2 = Integer
                                .parseInt(getFromSharedMem("resultcrop2" + Long.toString(sessionID)));
                        int crop3 = Integer
                                .parseInt(getFromSharedMem("resultcrop3" + Long.toString(sessionID)));

                        r = new Rect(crop0, crop1, crop0 + crop2, crop1 + crop3);
                    }
                }

                jpegQuality = Integer.parseInt(prefs.getString(ApplicationScreen.sJPEGQualityPref, "95"));
                if (!out.compressToJpeg(r, jpegQuality, os)) {
                    ApplicationScreen.getMessageHandler()
                            .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
                    return;
                }
                SwapHeap.FreeFromHeap(yuv);
            }

            String orientation_tag = String.valueOf(0);
            //            int sensorOrientation = CameraController.getSensorOrientation(CameraController.getCameraIndex());
            //            int displayOrientation = CameraController.getDisplayOrientation();
            ////            sensorOrientation = (360 + sensorOrientation + (cameraMirrored ? -displayOrientation
            ////                  : displayOrientation)) % 360;
            //            if (cameraMirrored) displayOrientation = -displayOrientation;
            //            
            //            // Calculate desired JPEG orientation relative to camera orientation to make
            //            // the image upright relative to the device orientation
            //            orientation = (sensorOrientation + displayOrientation + 360) % 360;

            switch (orientation) {
            default:
            case 0:
                orientation_tag = String.valueOf(0);
                break;
            case 90:
                orientation_tag = cameraMirrored ? String.valueOf(270) : String.valueOf(90);
                break;
            case 180:
                orientation_tag = String.valueOf(180);
                break;
            case 270:
                orientation_tag = cameraMirrored ? String.valueOf(90) : String.valueOf(270);
                break;
            }

            int exif_orientation = ExifInterface.ORIENTATION_NORMAL;
            if (writeOrientationTag) {
                switch ((orientation + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            } else {
                switch ((additionalRotationValue + 360) % 360) {
                default:
                case 0:
                    exif_orientation = ExifInterface.ORIENTATION_NORMAL;
                    break;
                case 90:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_270
                            : ExifInterface.ORIENTATION_ROTATE_90;
                    break;
                case 180:
                    exif_orientation = ExifInterface.ORIENTATION_ROTATE_180;
                    break;
                case 270:
                    exif_orientation = cameraMirrored ? ExifInterface.ORIENTATION_ROTATE_90
                            : ExifInterface.ORIENTATION_ROTATE_270;
                    break;
                }
            }

            if (!enableExifTagOrientation)
                exif_orientation = ExifInterface.ORIENTATION_NORMAL;

            values = new ContentValues();
            values.put(ImageColumns.TITLE,
                    file.getName().substring(0,
                            file.getName().lastIndexOf(".") >= 0 ? file.getName().lastIndexOf(".")
                                    : file.getName().length()));
            values.put(ImageColumns.DISPLAY_NAME, file.getName());
            values.put(ImageColumns.DATE_TAKEN, System.currentTimeMillis());
            values.put(ImageColumns.MIME_TYPE, "image/jpeg");

            if (enableExifTagOrientation) {
                if (writeOrientationTag) {
                    values.put(ImageColumns.ORIENTATION, String.valueOf(
                            (Integer.parseInt(orientation_tag) + additionalRotationValue + 360) % 360));
                } else {
                    values.put(ImageColumns.ORIENTATION, String.valueOf((additionalRotationValue + 360) % 360));
                }
            } else {
                values.put(ImageColumns.ORIENTATION, String.valueOf(0));
            }

            String filePath = file.getName();

            // If we able to get File object, than get path from it.
            // fileObject should not be null for files on phone memory.
            File fileObject = Util.getFileFromDocumentFile(file);
            if (fileObject != null) {
                filePath = fileObject.getAbsolutePath();
                values.put(ImageColumns.DATA, filePath);
            } else {
                // This case should typically happen for files saved to SD
                // card.
                String documentPath = Util.getAbsolutePathFromDocumentFile(file);
                values.put(ImageColumns.DATA, documentPath);
            }

            if (!enableExifTagOrientation && !hasDNGResult) {
                Matrix matrix = new Matrix();
                if (writeOrientationTag && (orientation + additionalRotationValue) != 0) {
                    matrix.postRotate((orientation + additionalRotationValue + 360) % 360);
                    rotateImage(bufFile, matrix);
                } else if (!writeOrientationTag && additionalRotationValue != 0) {
                    matrix.postRotate((additionalRotationValue + 360) % 360);
                    rotateImage(bufFile, matrix);
                }
            }

            if (useGeoTaggingPrefExport) {
                Location l = MLocation.getLocation(getApplicationContext());
                if (l != null) {
                    double lat = l.getLatitude();
                    double lon = l.getLongitude();
                    boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
                    if (hasLatLon) {
                        values.put(ImageColumns.LATITUDE, l.getLatitude());
                        values.put(ImageColumns.LONGITUDE, l.getLongitude());
                    }
                }
            }

            File modifiedFile = null;
            if (!hasDNGResult) {
                modifiedFile = saveExifTags(bufFile, sessionID, i, x, y, exif_orientation,
                        useGeoTaggingPrefExport, enableExifTagOrientation);
            }
            if (modifiedFile != null) {
                bufFile.delete();

                if (ApplicationScreen.getForceFilename() == null) {
                    // Copy buffer image with exif tags into result file.
                    InputStream is = null;
                    int len;
                    byte[] buf = new byte[4096];
                    try {
                        os = getApplicationContext().getContentResolver().openOutputStream(file.getUri());
                        is = new FileInputStream(modifiedFile);
                        while ((len = is.read(buf)) > 0) {
                            os.write(buf, 0, len);
                        }
                        is.close();
                        os.close();
                    } catch (IOException eIO) {
                        eIO.printStackTrace();
                        final IOException eIOFinal = eIO;
                        ApplicationScreen.instance.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(MainScreen.getMainContext(),
                                        "Error ocurred:" + eIOFinal.getLocalizedMessage(), Toast.LENGTH_LONG)
                                        .show();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    copyToForceFileName(modifiedFile);
                }

                modifiedFile.delete();
            } else {
                // Copy buffer image into result file.
                InputStream is = null;
                int len;
                byte[] buf = new byte[4096];
                try {
                    os = getApplicationContext().getContentResolver().openOutputStream(file.getUri());
                    is = new FileInputStream(bufFile);
                    while ((len = is.read(buf)) > 0) {
                        os.write(buf, 0, len);
                    }
                    is.close();
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bufFile.delete();
            }

            Uri uri = getApplicationContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
                    values);
            broadcastNewPicture(uri);
        }

        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    } catch (IOException e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler()
                .sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED_IOEXCEPTION);
        return;
    } catch (Exception e) {
        e.printStackTrace();
        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_EXPORT_FINISHED);
    }
}