List of usage examples for android.app DownloadManager addCompletedDownload
public long addCompletedDownload(String title, String description, boolean isMediaScannerScannable, String mimeType, String path, long length, boolean showNotification)
From source file:org.kde.kdeconnect.Plugins.SharePlugin.SharePlugin.java
@Override public boolean onPackageReceived(NetworkPackage np) { try {//from ww w. j av a2 s . c om 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:im.neon.activity.CommonActivityUtils.java
/** * Save a media URI into the download directory * * @param context the context/*from w ww. j av a 2s . c om*/ * @param srcFile the source file. * @param filename the filename (optional) * @return the downloads file path */ @SuppressLint("NewApi") public static String saveMediaIntoDownloads(Context context, File srcFile, String filename, String mimeType) { String fullFilePath = saveFileInto(srcFile, Environment.DIRECTORY_DOWNLOADS, filename); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (null != fullFilePath) { DownloadManager downloadManager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); try { File file = new File(fullFilePath); downloadManager.addCompletedDownload(file.getName(), file.getName(), true, mimeType, file.getAbsolutePath(), file.length(), true); } catch (Exception e) { Log.e(LOG_TAG, "## saveMediaIntoDownloads(): Exception Msg=" + e.getMessage()); } } } return fullFilePath; }
From source file:org.chromium.chrome.browser.download.DownloadManagerDelegate.java
/** * @see android.app.DownloadManager#addCompletedDownload(String, String, boolean, String, * String, long, boolean)/*w w w.ja v a 2 s .com*/ */ protected long addCompletedDownload(String fileName, String description, String mimeType, String path, long length, String originalUrl, String referer, String downloadGuid) { DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext); boolean useSystemNotification = !notificationManager.areNotificationsEnabled(); long downloadId = -1; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { Class<?> c = manager.getClass(); try { Class[] args = { String.class, String.class, boolean.class, String.class, String.class, long.class, boolean.class, Uri.class, Uri.class }; Method method = c.getMethod("addCompletedDownload", args); Uri originalUri = Uri.parse(originalUrl); Uri refererUri = referer == null ? Uri.EMPTY : Uri.parse(referer); downloadId = (Long) method.invoke(manager, fileName, description, true, mimeType, path, length, useSystemNotification, originalUri, refererUri); } catch (SecurityException e) { Log.e(TAG, "Cannot access the needed method."); } catch (NoSuchMethodException e) { Log.e(TAG, "Cannot find the needed method."); } catch (InvocationTargetException e) { Log.e(TAG, "Error calling the needed method."); } catch (IllegalAccessException e) { Log.e(TAG, "Error accessing the needed method."); } } else { downloadId = manager.addCompletedDownload(fileName, description, true, mimeType, path, length, useSystemNotification); } addDownloadIdMapping(downloadId, downloadGuid); return downloadId; }
From source file:cn.suishen.email.activity.MessageViewFragmentBase.java
private File performAttachmentSave(MessageViewAttachmentInfo info) { Attachment attachment = Attachment.restoreAttachmentWithId(mContext, info.mId); Uri attachmentUri = AttachmentUtilities.getAttachmentUri(mAccountId, attachment.mId); try {/*from w w w . ja v a 2s. c o m*/ File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); downloads.mkdirs(); File file = Utility.createUniqueFile(downloads, attachment.mFileName); Uri contentUri = AttachmentUtilities.resolveAttachmentIdToContentUri(mContext.getContentResolver(), attachmentUri); InputStream in = mContext.getContentResolver().openInputStream(contentUri); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); String absolutePath = file.getAbsolutePath(); // Although the download manager can scan media files, scanning only happens after the // user clicks on the item in the Downloads app. So, we run the attachment through // the media scanner ourselves so it gets added to gallery / music immediately. MediaScannerConnection.scanFile(mContext, new String[] { absolutePath }, null, null); DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE); dm.addCompletedDownload(info.mName, info.mName, false /* do not use media scanner */, info.mContentType, absolutePath, info.mSize, true /* show notification */); // Cache the stored file information. info.setSavedPath(absolutePath); // Update our buttons. updateAttachmentButtons(info); return file; } catch (IOException ioe) { // Ignore. Callers will handle it from the return code. } return null; }
From source file:org.mozilla.gecko.GeckoApp.java
void handleDownloadDone(String displayName, String path, String mimeType, int size) { // DownloadManager.addCompletedDownload is supported in level 12 and higher if (Build.VERSION.SDK_INT >= 12) { DownloadManager dm = (DownloadManager) mAppContext.getSystemService(Context.DOWNLOAD_SERVICE); dm.addCompletedDownload(displayName, displayName, false /* do not use media scanner */, mimeType, path, size, false /* no notification */); }/*from ww w. ja v a 2 s. c o m*/ }