Search in sources :

Example 6 with DocumentFile

use of android.support.v4.provider.DocumentFile in project kdeconnect-android by KDE.

the class SharePlugin method onPackageReceived.

@Override
public boolean onPackageReceived(NetworkPackage np) {
    try {
        if (np.hasPayload()) {
            Log.i("SharePlugin", "hasPayload");
            int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            } else if (permissionCheck == PackageManager.PERMISSION_DENIED) {
                // TODO Request Permission for storage
                Log.i("SharePlugin", "no Permission for Storage");
                return false;
            }
            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 * 10 / fileLength);
                                if (progressPercentage != prevProgressPercentage) {
                                    prevProgressPercentage = progressPercentage;
                                    builder.setProgress(100, (int) progressPercentage * 10, 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());
                        builder.setContentTitle(message).setTicker(message).setSmallIcon(android.R.drawable.stat_sys_download_done).setAutoCancel(true).setProgress(100, 100, false).setOngoing(false);
                        // TODO use FileProvider for >Nougat
                        if (Build.VERSION.SDK_INT < 24) {
                            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;
}
Also used : OutputStream(java.io.OutputStream) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) Uri(android.net.Uri) DownloadManager(android.app.DownloadManager) Notification(android.app.Notification) NotificationCompat(android.support.v4.app.NotificationCompat) Context(android.content.Context) ClipboardManager(android.content.ClipboardManager) DocumentFile(android.support.v4.provider.DocumentFile) NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) InputStream(java.io.InputStream) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Resources(android.content.res.Resources) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder)

Example 7 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class StorageHelper method copyFile.

public static boolean copyFile(Context context, @NonNull final File source, @NonNull final File targetDir) {
    InputStream inStream = null;
    OutputStream outStream = null;
    boolean success = false;
    File target = getTargetFile(source, targetDir);
    try {
        inStream = new FileInputStream(source);
        // First try the normal way
        if (isWritable(target)) {
            // standard way
            FileChannel inChannel = new FileInputStream(source).getChannel();
            FileChannel outChannel = new FileOutputStream(target).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            success = true;
            try {
                inChannel.close();
            } catch (Exception ignored) {
            }
            try {
                outChannel.close();
            } catch (Exception ignored) {
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // outStream = context.getContentResolver().openOutputStream(Uri.fromFile(target));
                if (isFileOnSdCard(context, source)) {
                    DocumentFile sourceDocument = getDocumentFile(context, source, false, false);
                    if (sourceDocument != null) {
                        inStream = context.getContentResolver().openInputStream(sourceDocument.getUri());
                    }
                }
                // Storage Access Framework
                DocumentFile targetDocument = getDocumentFile(context, target, false, false);
                if (targetDocument != null) {
                    outStream = context.getContentResolver().openOutputStream(targetDocument.getUri());
                }
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                // TODO: 13/08/16 test this
                // Workaround for Kitkat ext SD card
                Uri uri = getUriFromFile(context, target.getAbsolutePath());
                if (uri != null) {
                    outStream = context.getContentResolver().openOutputStream(uri);
                }
            }
            if (outStream != null) {
                // Both for SAF and for Kitkat, write to output stream.
                // MAGIC_NUMBER
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);
                success = true;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error when copying file from " + source.getAbsolutePath() + " to " + target.getAbsolutePath(), e);
        return false;
    } finally {
        try {
            inStream.close();
        } catch (Exception ignored) {
        }
        try {
            outStream.close();
        } catch (Exception ignored) {
        }
    }
    if (success)
        scanFile(context, new String[] { target.getPath() });
    return success;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileChannel(java.nio.channels.FileChannel) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Uri(android.net.Uri) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) DocumentFile(android.support.v4.provider.DocumentFile)

Example 8 with DocumentFile

use of android.support.v4.provider.DocumentFile in project LeafPic by HoraApps.

the class StorageHelper method deleteFile.

/**
 * Delete a file. May be even on external SD card.
 *
 * @param file the file to be deleted.
 * @return True if successfully deleted.
 */
public static boolean deleteFile(Context context, @NonNull final File file) {
    // W/DocumentFile: Failed getCursor: java.lang.IllegalArgumentException: Failed to determine if A613-F0E1:.android_secure is child of A613-F0E1:: java.io.FileNotFoundException: Missing file for A613-F0E1:.android_secure at /storage/sdcard1/.android_secure
    // First try the normal deletion.
    boolean success = file.delete();
    // Try with Storage Access Framework.
    if (!success && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DocumentFile document = getDocumentFile(context, file, false, false);
        success = document != null && document.delete();
    }
    // Try the Kitkat workaround.
    if (!success && Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        try {
            // MediaStoreUtil.getUriFromFile(file.getAbsolutePath());
            Uri uri = null;
            if (uri != null) {
                resolver.delete(uri, null, null);
            }
            success = !file.exists();
        } catch (Exception e) {
            Log.e(TAG, "Error when deleting file " + file.getAbsolutePath(), e);
            return false;
        }
    }
    if (success)
        scanFile(context, new String[] { file.getPath() });
    return success;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) Uri(android.net.Uri) IOException(java.io.IOException) ContentResolver(android.content.ContentResolver)

Example 9 with DocumentFile

use of android.support.v4.provider.DocumentFile in project Shuttle by timusus.

the class TaggerUtils method getDocumentFile.

static DocumentFile getDocumentFile(Uri treeUri, final File file) {
    String baseFolder = getExtSdCardFolder(file);
    if (baseFolder == null) {
        return null;
    }
    if (treeUri == null) {
        return null;
    }
    String relativePath;
    try {
        String fullPath = file.getCanonicalPath();
        relativePath = fullPath.substring(baseFolder.length() + 1);
    } catch (IOException e) {
        return null;
    }
    // start with root of SD card and then parse through document tree.
    DocumentFile document = DocumentFile.fromTreeUri(ShuttleApplication.getInstance(), treeUri);
    String[] parts = relativePath.split("/");
    for (String part : parts) {
        DocumentFile nextDocument = document.findFile(part);
        if (nextDocument != null) {
            document = nextDocument;
        }
    }
    if (document.isFile()) {
        return document;
    }
    return null;
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) IOException(java.io.IOException)

Example 10 with DocumentFile

use of android.support.v4.provider.DocumentFile in project AmazeFileManager by TeamAmaze.

the class FileUtil method deleteFile.

/**
 * Delete a file. May be even on external SD card.
 *
 * @param file the file to be deleted.
 * @return True if successfully deleted.
 */
static boolean deleteFile(@NonNull final File file, Context context) {
    // First try the normal deletion.
    if (file == null)
        return true;
    boolean fileDelete = rmdir(file, context);
    if (file.delete() || fileDelete)
        return true;
    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && FileUtil.isOnExtSdCard(file, context)) {
        DocumentFile document = getDocumentFile(file, false, context);
        return document.delete();
    }
    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        try {
            Uri uri = MediaStoreHack.getUriFromFile(file.getAbsolutePath(), context);
            resolver.delete(uri, null, null);
            return !file.exists();
        } catch (Exception e) {
            Log.e(LOG, "Error when deleting file " + file.getAbsolutePath(), e);
            return false;
        }
    }
    return !file.exists();
}
Also used : DocumentFile(android.support.v4.provider.DocumentFile) Uri(android.net.Uri) ShellNotRunningException(com.amaze.filemanager.exceptions.ShellNotRunningException) SmbException(jcifs.smb.SmbException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ContentResolver(android.content.ContentResolver)

Aggregations

DocumentFile (android.support.v4.provider.DocumentFile)65 File (java.io.File)36 IOException (java.io.IOException)22 Uri (android.net.Uri)21 ContentResolver (android.content.ContentResolver)12 SmbFile (jcifs.smb.SmbFile)11 MalformedURLException (java.net.MalformedURLException)10 SmbException (jcifs.smb.SmbException)10 FileOutputStream (java.io.FileOutputStream)9 ShellNotRunningException (com.amaze.filemanager.exceptions.ShellNotRunningException)8 OutputStream (java.io.OutputStream)8 InputStream (java.io.InputStream)7 SuppressLint (android.annotation.SuppressLint)6 CloudStorage (com.cloudrail.si.interfaces.CloudStorage)6 FileInputStream (java.io.FileInputStream)6 SFtpClientTemplate (com.amaze.filemanager.filesystem.ssh.SFtpClientTemplate)4 BufferedOutputStream (java.io.BufferedOutputStream)4 FileNotFoundException (java.io.FileNotFoundException)4 FileChannel (java.nio.channels.FileChannel)4 SFTPClient (net.schmizz.sshj.sftp.SFTPClient)4