List of usage examples for android.app DownloadManager enqueue
public long enqueue(Request request)
From source file:net.olejon.mdapp.MyTools.java
public void downloadFile(String title, String uri) { DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri)); request.setAllowedOverRoaming(false); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setTitle(title);/*from ww w . ja v a2 s. co m*/ downloadManager.enqueue(request); showToast(mContext.getString(R.string.mytools_downloading), 1); }
From source file:com.codeskraps.sbrowser.home.SBrowserActivity.java
@SuppressLint("NewApi") @Override//from w w w .j av a2s .c o m public boolean onContextItemSelected(MenuItem item) { Log.v(TAG, "onContextItemSelected"); WebView.HitTestResult result = webView.getHitTestResult(); Log.d(TAG, "result: " + result.getExtra()); Intent sharingIntent = new Intent(Intent.ACTION_SEND); switch (item.getItemId()) { case R.id.itemSaveImage: case R.id.itemSaveLink: try { DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); Request request = new Request(Uri.parse(result.getExtra())); dm.enqueue(request); } catch (Exception e) { Toast.makeText(this, "sBrowser - Error saving...", Toast.LENGTH_SHORT).show(); Log.d(TAG, "Erro Downloading: " + e); } break; case R.id.itemCopyLink: if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(result.getExtra()); } else { android.content.ClipboardManager newClipboard = (android.content.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("label", result.getExtra()); newClipboard.setPrimaryClip(clip); } break; case R.id.itemShareLink: try { sharingIntent.setType("text/html"); sharingIntent.putExtra(Intent.EXTRA_TEXT, result.getExtra()); startActivity(Intent.createChooser(sharingIntent, "Share using...")); } catch (Exception e) { e.printStackTrace(); Log.d(TAG, "Erro Sharing link: " + e); } break; case R.id.itemShareImage: try { sharingIntent.setType("image/*"); sharingIntent.putExtra(Intent.EXTRA_STREAM, result.getExtra()); startActivity(Intent.createChooser(sharingIntent, "Share image using...")); } catch (Exception e) { e.printStackTrace(); Log.d(TAG, "Erro Sharing Image: " + e); } break; } return super.onContextItemSelected(item); }
From source file:com.brewcrewfoo.performance.activities.PCSettings.java
@Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { String key = preference.getKey(); if (key.equals("use_light_theme")) { mPreferences.edit().putBoolean("theme_changed", true).commit(); finish();//w ww . j a va 2 s. com return true; } else if (key.equals("visible_tabs")) { startActivity(new Intent(this, HideTabs.class)); return true; } else if (key.equals("boot_mode")) { if (mInitd.isChecked()) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null); final EditText tv = (EditText) editDialog.findViewById(R.id.vprop); final TextView tn = (TextView) editDialog.findViewById(R.id.nprop); tv.setText(mPreferences.getString("script_name", "99PC")); tn.setText(""); tn.setVisibility(TextView.GONE); new AlertDialog.Builder(this).setTitle(getString(R.string.pt_script_name)).setView(editDialog) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String s = tv.getText().toString(); if ((s != null) && (s.length() > 0)) { mPreferences.edit().putString("script_name", s).apply(); } mInitd.setSummary(INIT_D + mPreferences.getString("script_name", "99PC")); new BootClass(c, mPreferences).writeScript(); } }).create().show(); } else { final StringBuilder sb = new StringBuilder(); sb.append("mount -o rw,remount /system;\n"); sb.append("busybox rm ").append(INIT_D).append(mPreferences.getString("script_name", "99PC")) .append(";\n"); sb.append("mount -o ro,remount /system;\n"); Helpers.shExec(sb, c, true); } return true; } else if (key.equals("int_sd")) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null); final EditText tv = (EditText) editDialog.findViewById(R.id.vprop); final TextView tn = (TextView) editDialog.findViewById(R.id.nprop); tv.setText(""); tn.setText(getString(R.string.info_auto_sd)); new AlertDialog.Builder(this).setTitle(getString(R.string.pt_int_sd)).setView(editDialog) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String s = tv.getText().toString(); if ((s != null) && (s.length() > 0)) { if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); } if (!s.startsWith("/")) { s = "/" + s; } final File dir = new File(s); if (dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite()) mPreferences.edit().putString("int_sd_path", s).apply(); } else { mPreferences.edit().remove("int_sd_path").apply(); } mIntSD.setSummary(mPreferences.getString("int_sd_path", Environment.getExternalStorageDirectory().getAbsolutePath())); } }).create().show(); } else if (key.equals("ext_sd")) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.prop_edit_dialog, null); final EditText tv = (EditText) editDialog.findViewById(R.id.vprop); final TextView tn = (TextView) editDialog.findViewById(R.id.nprop); tv.setText(""); tn.setText(getString(R.string.info_auto_sd)); new AlertDialog.Builder(this).setTitle(getString(R.string.pt_ext_sd)).setView(editDialog) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String s = tv.getText().toString(); if ((s != null) && (s.length() > 0)) { if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); } if (!s.startsWith("/")) { s = "/" + s; } final File dir = new File(s); if (dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite()) mPreferences.edit().putString("ext_sd_path", s).apply(); } else { mPreferences.edit().remove("ext_sd_path").apply(); } mExtSD.setSummary(mPreferences.getString("ext_sd_path", Helpers.extSD())); } }).create().show(); } else if (key.equals("br_op")) { startActivity(new Intent(this, BackupRestore.class)); } else if (key.equals("version_info")) { if (isupdate && !NO_UPDATE) { LayoutInflater factory = LayoutInflater.from(this); final View editDialog = factory.inflate(R.layout.ver_dialog, null); final TextView msg = (TextView) editDialog.findViewById(R.id.msg); msg.setText(det); new AlertDialog.Builder(c).setView(editDialog).setTitle(getString(R.string.pt_update)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton(getString(R.string.btn_download), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (isDownloadManagerAvailable(c)) { String url = URL + TAG + ".apk"; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); //request.setDescription(""); request.setTitle(TAG + " " + ver); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { request.allowScanningByMediaScanner(); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, TAG + "-" + ver + ".apk"); DownloadManager manager = (DownloadManager) getSystemService( Context.DOWNLOAD_SERVICE); manager.enqueue(request); } else { Toast.makeText(c, getString(R.string.no_download_manager), Toast.LENGTH_LONG) .show(); } } }).create().show(); } return true; } else if (key.equals("pref_donate")) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PAYPAL + PAYPAL_BTN))); } return false; }
From source file:com.keylesspalace.tusky.ViewMediaActivity.java
private void downloadImage() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); } else {//www .java 2s . c om String url = attachments.get(viewPager.getCurrentItem()).getAttachment().getUrl(); Uri uri = Uri.parse(url); String filename = new File(url).getName(); String toastText = String.format(getResources().getString(R.string.download_image), filename); Toast.makeText(this.getApplicationContext(), toastText, Toast.LENGTH_SHORT).show(); DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(uri); request.allowScanningByMediaScanner(); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, getString(R.string.app_name) + "/" + filename); downloadManager.enqueue(request); } }
From source file:com.fa.mastodon.fragment.ViewMediaFragment.java
private void downloadImage() { //Permission stuff if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && ContextCompat.checkSelfPermission(this.getContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { android.support.v4.app.ActivityCompat.requestPermissions(getActivity(), new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); } else {/*from w w w . j a v a 2 s. c o m*/ //download stuff String url = getArguments().getString("url"); Uri uri = Uri.parse(url); String filename = new File(url).getName(); DownloadManager downloadManager = (DownloadManager) getContext() .getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(uri); request.allowScanningByMediaScanner(); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, getString(R.string.app_name) + "/" + filename); downloadManager.enqueue(request); } }
From source file:br.ufrn.dimap.pubshare.download.service.DownloaderService.java
/** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate.//from w w w. j av a 2 s . c o m */ @Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent on DownloadService"); Article selectedArticle = (Article) intent.getSerializableExtra(Article.KEY_INSTANCE); if (!AndroidUtils.isExternalStorageAvailable()) { // Generate Menssages NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_menu_notifications) .setContentTitle(getResources().getString(R.string.external_storage_unavailable)) .setContentText(getResources().getString(R.string.check_media_availability)); Notification notification = mBuilder.build(); // Set the Notification as ongoing notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL; NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nManager.notify(0, notification); return; } DownloadManager dowloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); // since API level 9 Request request = new Request(Uri.parse(selectedArticle.getRemoteLocation())); request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE); request.setTitle(selectedArticle.getTitle()); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, selectedArticle.generateFileName()); request.setVisibleInDownloadsUi(true); long enqueue = dowloadManager.enqueue(request); Log.d(TAG, "Download enqueue..." + enqueue); ArticleDownloaded articleDownloaded = new ArticleDownloaded(); articleDownloaded.setDownloadKey(enqueue); DownloadDao downloadDao = new DownloadDao(this); downloadDao.insert(articleDownloaded); Log.d(TAG, "Insert " + articleDownloaded + " in SqLite: OK"); }
From source file:me.kartikarora.transfersh.adapters.FileGridAdapter.java
private void beginDownload(String name, String type, String url) { tracker.send(new HitBuilders.EventBuilder().setCategory("Action").setAction("Download : " + url).build()); DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(url);/*from w w w. j a v a 2 s. co m*/ DownloadManager.Request request = new DownloadManager.Request(uri); request.setDescription(context.getString(R.string.app_name)); request.setTitle(name); String dir = "/" + context.getString(R.string.app_name) + "/" + type + "/" + name; request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, dir); manager.enqueue(request); }
From source file:org.mozilla.focus.fragment.BrowserFragment.java
/** * Use Android's Download Manager to queue this download. *///from www. j ava 2 s . c o m private void queueDownload(Download download) { if (download == null) { return; } final Context context = getContext(); if (context == null) { return; } final String cookie = CookieManager.getInstance().getCookie(download.getUrl()); final String fileName = URLUtil.guessFileName(download.getUrl(), download.getContentDisposition(), download.getMimeType()); final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(download.getUrl())) .addRequestHeader("User-Agent", download.getUserAgent()).addRequestHeader("Cookie", cookie) .addRequestHeader("Referer", getUrl()) .setDestinationInExternalPublicDir(download.getDestinationDirectory(), fileName) .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) .setMimeType(download.getMimeType()); request.allowScanningByMediaScanner(); final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); }
From source file:com.haw3d.jadvalKalemat.versions.GingerbreadUtil.java
@Override @SuppressWarnings("unused") // Ignore dead code warning public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification, String title, HttpContext httpContext) throws IOException { // The DownloadManager can sometimes be buggy and can cause spurious // errors, see // http://code.google.com/p/android/issues/detail?id=18462 // Since puzzle files are very small (a few KB), we don't need to use // any of the useful features the DownloadManager provides, such as // resuming interrupted downloads and resuming downloads across // system reboots. So for now, just use the ordinary // DefaultHttpClient. ///* w w w. j a va 2s. com*/ // Also, pre-ICS download managers don't support HTTPS. if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) { super.downloadFile(url, headers, destination, notification, title, httpContext); return; } DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Request request = new Request(Uri.parse(url.toString())); File tempFile = new File(jadvalKalematApplication.TEMP_DIR, destination.getName()); request.setDestinationUri(Uri.fromFile(tempFile)); for (Entry<String, String> entry : headers.entrySet()) { request.addRequestHeader(entry.getKey(), entry.getValue()); } request.setMimeType("application/x-crossword"); setNotificationVisibility(request, notification); request.setTitle(title); long id = mgr.enqueue(request); Long idObj = id; String scrubbedUrl = AbstractDownloader.scrubUrl(url); LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")"); // If the request completed really fast, we're done DownloadingFile downloadingFile; boolean completed = false; boolean succeeded = false; int status = -1; synchronized (completedDownloads) { downloadingFile = completedDownloads.remove(idObj); if (downloadingFile != null) { completed = true; succeeded = downloadingFile.succeeded; status = downloadingFile.status; } else { downloadingFile = new DownloadingFile(); waitingDownloads.put(idObj, downloadingFile); } } // Wait for the request to complete, if it hasn't completed already if (!completed) { try { synchronized (downloadingFile) { if (!downloadingFile.completed) { downloadingFile.wait(); } succeeded = downloadingFile.succeeded; status = downloadingFile.status; } } catch (InterruptedException e) { LOG.warning("Download interrupted: " + scrubbedUrl); throw new IOException("Download interrupted"); } } LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl); if (succeeded) { if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) { LOG.warning("Failed to rename " + tempFile + " to " + destination); throw new IOException("Failed to rename " + tempFile + " to " + destination); } } else { throw new HTTPException(status); } }
From source file:com.adamrosenfield.wordswithcrosses.versions.GingerbreadUtil.java
@Override @SuppressWarnings("unused") // Ignore dead code warning public void downloadFile(URL url, Map<String, String> headers, File destination, boolean notification, String title, HttpContext httpContext) throws IOException { // The DownloadManager can sometimes be buggy and can cause spurious // errors, see // http://code.google.com/p/android/issues/detail?id=18462 // Since puzzle files are very small (a few KB), we don't need to use // any of the useful features the DownloadManager provides, such as // resuming interrupted downloads and resuming downloads across // system reboots. So for now, just use the ordinary // DefaultHttpClient. ///*www. j av a 2s .co m*/ // Also, pre-ICS download managers don't support HTTPS. if (!USE_DOWNLOAD_MANAGER || "https".equals(url.getProtocol()) && android.os.Build.VERSION.SDK_INT < 15) { super.downloadFile(url, headers, destination, notification, title, httpContext); return; } DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Request request = new Request(Uri.parse(url.toString())); File tempFile = new File(WordsWithCrossesApplication.TEMP_DIR, destination.getName()); request.setDestinationUri(Uri.fromFile(tempFile)); for (Entry<String, String> entry : headers.entrySet()) { request.addRequestHeader(entry.getKey(), entry.getValue()); } request.setMimeType("application/x-crossword"); setNotificationVisibility(request, notification); request.setTitle(title); long id = mgr.enqueue(request); Long idObj = id; String scrubbedUrl = AbstractDownloader.scrubUrl(url); LOG.info("Downloading " + scrubbedUrl + " ==> " + tempFile + " (id=" + id + ")"); // If the request completed really fast, we're done DownloadingFile downloadingFile; boolean completed = false; boolean succeeded = false; int status = -1; synchronized (completedDownloads) { downloadingFile = completedDownloads.remove(idObj); if (downloadingFile != null) { completed = true; succeeded = downloadingFile.succeeded; status = downloadingFile.status; } else { downloadingFile = new DownloadingFile(); waitingDownloads.put(idObj, downloadingFile); } } // Wait for the request to complete, if it hasn't completed already if (!completed) { try { synchronized (downloadingFile) { if (!downloadingFile.completed) { downloadingFile.wait(); } succeeded = downloadingFile.succeeded; status = downloadingFile.status; } } catch (InterruptedException e) { LOG.warning("Download interrupted: " + scrubbedUrl); throw new IOException("Download interrupted"); } } LOG.info("Download " + (succeeded ? "succeeded" : "failed") + ": " + scrubbedUrl); if (succeeded) { if (!destination.equals(tempFile) && !tempFile.renameTo(destination)) { LOG.warning("Failed to rename " + tempFile + " to " + destination); throw new IOException("Failed to rename " + tempFile + " to " + destination); } } else { throw new HTTPException(status); } }