List of usage examples for android.app DownloadManager enqueue
public long enqueue(Request request)
From source file:org.que.activities.fragments.PaperDetailMenuFragment.java
/** * @author deLaczkovich on 26.06.2014.// ww w .j a v a 2 s .c o m * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { Date d = new Date(); if (item.getItemId() == R.id.action_paper_detail) { long startDate = Long.parseLong(getString(R.string.startDate)); if (d.getTime() < startDate) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(getString(R.string.notAvailable)); builder.setNeutralButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); return super.onOptionsItemSelected(item); } String key = getString(R.string.pref_api_key); SharedPreferences pref = getActivity().getSharedPreferences(PaperDetailMenuFragment.class.getName(), Context.MODE_PRIVATE); final String apiKey = pref.getString(key, null); if (apiKey == null) { DialogFragment auth_required = new AuthRequiredDialogFragment(); auth_required.show(getActivity().getSupportFragmentManager(), AuthRequiredDialogFragment.TAG_AUTH_REQUIRED); Toast.makeText(getActivity(), getString(R.string.authSuccess), Toast.LENGTH_LONG).show(); } else { //TODO Paper detail view call AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.viewQuestionTitle)) .setMessage(getString(R.string.viewQuestionMsg)) .setPositiveButton(getString(R.string.pdfViewerAvail), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DownloadManager downloadManager = (DownloadManager) getActivity() .getSystemService(Context.DOWNLOAD_SERVICE); String url = String.format(getString(R.string.alert_paper_view_url_direct), paper.getId(), apiKey); Uri Download_Uri = Uri.parse(url); String fileName = paper.getTitle() + ".pdf"; DownloadManager.Request request = new DownloadManager.Request(Download_Uri) .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI) .setTitle(getString(R.string.paperDwnlTitle)) .setDescription(getString(R.string.paperDwnlMsg)) .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName) .setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); downloadManager.enqueue(request); } }) .setNegativeButton(getString(R.string.noPdfViewerAvail), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Bundle args = new Bundle(); String url = String.format(getString(R.string.alert_paper_view_url), paper.getId(), apiKey); args.putString(WebviewFragment.ARG_WEBVIEW_FRAGMENT_URL, url); args.putString(WebviewFragment.ARG_WEBVIEW_FRAGMENT_TITLE, paper.getTitle()); Fragment fragment = new WebviewFragment(); fragment.setArguments(args); FragmentManager mgr = ((FragmentActivity) getActivity()) .getSupportFragmentManager(); Fragment old = mgr.findFragmentById(R.id.content_frame); FragmentTransaction trx = mgr.beginTransaction(); if (old != null) { trx.remove(old); } trx.add(R.id.content_frame, fragment).addToBackStack(null).commit(); } }) .show(); } } return super.onOptionsItemSelected(item); }
From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java
private void startAsync(JSONArray args, CallbackContext callbackContext) throws JSONException { if (activDownloads.size() == 0) { // required to receive notification when download is completed Log.d("BackgroundDownload", "Registering the receiver"); cordova.getActivity().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); }/* www .ja v a 2 s . c o m*/ Download curDownload = new Download(args.get(0).toString(), args.get(1).toString(), callbackContext); if (activDownloads.containsKey(curDownload.getUriString())) { if (args.length() >= 4) { boolean resumeCurrent = args.getBoolean(3); if (resumeCurrent) { StartProgressTracking(curDownload); return; } } else { return; } } activDownloads.put(curDownload.getUriString(), curDownload); curDownload.setDownloadId(findActiveDownload(curDownload.getUriString())); if (curDownload.getDownloadId() == DOWNLOAD_ID_UNDEFINED) { // make sure file does not exist, in other case DownloadManager will fail File targetFile = new File(Uri.parse(curDownload.getTempFilePath()).getPath()); targetFile.delete(); DownloadManager mgr = (DownloadManager) this.cordova.getActivity() .getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(curDownload.getUriString())); // Use the cookie from the webview, so the session cookie is shared request.addRequestHeader("Cookie", this.webView.getCookieManager().getCookie(curDownload.getUriString())); try { // Get the app label and set it as the title int appLabelResId = this.webView.getContext().getApplicationInfo().labelRes; request.setTitle(this.webView.getContext().getString(appLabelResId)); } catch (Resources.NotFoundException e) { // Use generic title if the app label wasn't found request.setTitle("Background download plugin"); } request.setVisibleInDownloadsUi(false); // if (Build.VERSION.SDK_INT >= 11) { // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); // } request.setDestinationUri(Uri.parse(curDownload.getTempFilePath())); Log.d("BackgroundDownload", "downloading"); curDownload.setDownloadId(mgr.enqueue(request)); } else if (checkDownloadCompleted(curDownload.getDownloadId())) { callbackContext.success(); } StartProgressTracking(curDownload); }
From source file:fr.kwiatkowski.apktrack.service.WebService.java
/** * Downloads the APK for a given app if a download URL is available. * APK downloads take place through the Download Service. Files are stored on a dedicated * folder on the external storage of the device. * @param app The app whose APK is to be downloaded. *//* w ww . j av a 2 s .co m*/ private void _download_apk(InstalledApp app, String request_source) { if (app.get_download_url() == null) { return; } Uri uri = Uri .parse(String.format(app.get_download_url(), app.get_display_name(), app.get_latest_version())); DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(uri); // Indicate whether the download may take place over mobile data. // Download over data is okay on user click, but respect the preference for background checks. if (ScheduledCheckService.SERVICE_SOURCE.equals(request_source) && PreferenceManager .getDefaultSharedPreferences(this).getBoolean(SettingsFragment.KEY_PREF_WIFI_ONLY, true)) { request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); } else { request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); } // Don't download APKs when roaming. request.setAllowedOverRoaming(false).setTitle(getString(getApplicationInfo().labelRes)) .setDescription(app.get_display_name() + " " + app.get_latest_version() + ".apk") .setVisibleInDownloadsUi(false).setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, app.get_package_name() + "-" + app.get_latest_version() + ".apk"); long id = dm.enqueue(request); app.set_download_id(id); app.save(); EventBusHelper.post_sticky(ModelModifiedMessage.event_type.APP_UPDATED, app.get_package_name()); }
From source file:tm.alashow.datmusic.ui.activity.MainActivity.java
private void search(String query, final boolean refresh, long captchaSid, String captchaKey, boolean performerOnly) { oldQuery = query;/* w w w. j ava 2s . com*/ RequestParams params = new RequestParams(); params.put("q", query); params.put("autocomplete", Config.VK_CONFIG_AUTOCOMPLETE); params.put("sort", CONFIG_SORT); params.put("count", CONFIG_COUNT); params.put("performer_only", (performerOnly) ? 1 : CONFIG_PERFORMER_ONLY); if (captchaSid > 1) { params.put("captcha_sid", captchaSid); params.put("captcha_key", captchaKey); } //change search method to getPopular, if query empty. get popular music. ApiClient.get(Config.SEARCH, params, new JsonHttpResponseHandler() { @Override public void onStart() { U.hideView(errorView); if (refresh) { swipeRefreshLayout.setRefreshing(true); } else { U.showView(progressBar); U.hideView(mListView); } } @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { clearList();//clear old data if (response.has("error")) { //if we have error //Result errors JSONObject errorObject = response.getJSONObject("error"); int errorCode = errorObject.getInt("error_code"); //showing error switch (errorCode) { case 5: showError("token"); break; case 6: // "Too many requests per second" error, retry search(oldQuery); break; case 14: showCaptcha(errorObject.getString("captcha_img"), errorObject.getLong("captcha_sid")); showError("captcha"); break; default: showError(errorObject.getString("error_msg")); break; } return; } JSONArray audios = response.getJSONArray("response"); if (audios.length() >= 2) { for (int i = 1; i < audios.length(); i++) audioList.add(new Audio((JSONObject) audios.get(i))); audioListAdapter = new AudioListAdapter(MainActivity.this, audioList); mListView.setAdapter(audioListAdapter); mListView.setFastScrollEnabled(audioList.size() > 10); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Audio audio = audioList.get(position); final BottomSheet bottomSheet = new BottomSheet.Builder(MainActivity.this) .title(audio.getArtist() + " - " + audio.getTitle()) .sheet(R.menu.audio_actions) .listener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case R.id.download: DownloadManager mgr = (DownloadManager) getSystemService( DOWNLOAD_SERVICE); Uri downloadUri = Uri.parse(audio.getDownloadUrl()); DownloadManager.Request request = new DownloadManager.Request( downloadUri); if (U.isAboveOfVersion(11)) { request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); mgr.enqueue(request); break; case R.id.play: playAudio(audio); break; case R.id.copy: if (!U.isAboveOfVersion(11)) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); clipboard.setText(audio.getSecureDownloadUrl()); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService( CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData .newPlainText("Link", audio.getSecureDownloadUrl()); clipboard.setPrimaryClip(clip); U.showCenteredToast(MainActivity.this, R.string.audio_copied); } break; case R.id.share: String shareText = getString(R.string.share_text) + audio.getSecureDownloadUrl(); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, shareText); sendIntent.setType("text/plain"); startActivity(sendIntent); } } }).show(); //If file size already set, show it if (audio.getBytes() > 1) { setSizeAndBitrate(bottomSheet, audio); } else { try { new Thread(new Runnable() { @Override public void run() { try { URLConnection ucon; final URL uri = new URL(audio.getDownloadUrl()); ucon = uri.openConnection(); ucon.connect(); final long bytes = Long .parseLong(ucon.getHeaderField("content-length")); runOnUiThread(new Runnable() { @Override public void run() { audio.setBytes(bytes); setSizeAndBitrate(bottomSheet, audio); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } catch (final Exception e) { e.printStackTrace(); } } } }); if (refresh) { swipeRefreshLayout.setRefreshing(false); } else { U.hideView(progressBar); } } else { showError("notFound"); } } catch (Exception e) { U.showCenteredToast(MainActivity.this, R.string.exception); e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { showError("network"); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { showError("network"); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { showError("network"); } @Override public void onFinish() { U.showView(mListView); if (refresh) { swipeRefreshLayout.setRefreshing(false); } else { U.hideView(progressBar); } } }); }
From source file:org.wso2.iot.agent.api.ApplicationManager.java
/** * Initiate downloading via DownloadManager API. * * @param url - File URL./*from w w w . j av a 2s. com*/ * @param appName - Name of the application to be downloaded. */ private void downloadViaDownloadManager(String url, String appName) { final DownloadManager downloadManager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); Uri downloadUri = Uri.parse(url); DownloadManager.Request request = new DownloadManager.Request(downloadUri); // Restrict the types of networks over which this download may // proceed. request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); // Set whether this download may proceed over a roaming connection. request.setAllowedOverRoaming(true); // Set the title of this download, to be displayed in notifications // (if enabled). request.setTitle(resources.getString(R.string.downloader_message_title)); request.setVisibleInDownloadsUi(false); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); // Set the local destination for the downloaded file to a path // within the application's external files directory request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appName); // Enqueue a new download and same the referenceId downloadReference = downloadManager.enqueue(request); new Thread(new Runnable() { @Override public void run() { boolean downloading = true; int progress = 0; while (downloading) { downloadOngoing = true; DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadReference); Cursor cursor = downloadManager.query(query); cursor.moveToFirst(); int bytesDownloaded = cursor .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); int bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); if (cursor.getInt(cursor .getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) { downloading = false; } if (cursor.getInt(cursor .getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) { downloading = false; Preference.putString(context, context.getResources().getString(R.string.app_install_status), context.getResources().getString(R.string.app_status_value_download_failed)); Preference.putString(context, context.getResources().getString(R.string.app_install_failed_message), "App download failed due to a connection issue."); } int downloadProgress = 0; if (bytesTotal > 0) { downloadProgress = (int) ((bytesDownloaded * 100l) / bytesTotal); } if (downloadProgress != DOWNLOAD_PERCENTAGE_TOTAL) { progress += DOWNLOADER_INCREMENT; } else { progress = DOWNLOAD_PERCENTAGE_TOTAL; Preference.putString(context, context.getResources().getString(R.string.app_install_status), context.getResources().getString(R.string.app_status_value_download_completed)); } Preference.putString(context, resources.getString(R.string.app_download_progress), String.valueOf(progress)); cursor.close(); } downloadOngoing = false; } }).start(); }
From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java
private boolean queue(BrandedItem item) { if (item.type != BrandedItem.TYPE_MESSAGE && com.mobicage.rogerthat.util.TextUtils.isEmptyOrWhitespace(item.brandingKey)) return false; if (item.type == BrandedItem.TYPE_FRIEND) { // Need to summarize Friend to prevent java.io.UTFDataFormatException: String more than 65535 UTF bytes long FriendTO friend = (FriendTO) item.object; FriendTO friendSummary = new FriendTO(); friendSummary.email = friend.email; item.object = friendSummary;/*from ww w. ja v a 2s.c o m*/ } if (item.usesDownloadManager()) { DownloadManager dwnlManager = getDownloadManager(); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(item.brandingKey)); int flags = DownloadManager.Request.NETWORK_WIFI; if (!mMainService.getPlugin(SystemPlugin.class).getWifiOnlyDownloads()) { flags |= DownloadManager.Request.NETWORK_MOBILE; } request.setAllowedNetworkTypes(flags); final Long id = dwnlManager.enqueue(request); synchronized (mLock) { item.downloadId = id; mDownloadMgrQueue.put(id, item); save(); } } else { synchronized (mLock) { mQueue.add(item); Collections.sort(mQueue); save(); } if (mExternalStorageWriteable) { mDownloaderHandler.post(mQueueProcessor); } } return true; }
From source file:com.meycup.ducksound.BackgroundSearch.java
@Override protected void onPostExecute(final String[][] strings) { if (strings[0][0].equals("error_on_search")) { if (strings[0][1].equals("")) { tv.setVisibility(View.VISIBLE); listView.setAdapter(null);/*from w w w .j a v a2s. c o m*/ } else { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle("Ocorreu um erro!"); alert.setMessage(strings[0][1]); alert.setPositiveButton("Tentar novamente", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { BackgroundSearch research = new BackgroundSearch(context, listView, play_bar, tv); research.execute(search); dialog.dismiss(); } }); alert.setNegativeButton("Sair", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); System.exit(0); } }); alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); } } else { if (tv != null) { tv.setVisibility(View.INVISIBLE); } int count = 0; for (int i = 0; i < strings[0].length; i++) { if (strings[0][i] != null) { count++; } } ListAdapter adp = new ListAdapter(context, strings, new String[count]); listView.setAdapter(adp); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (strings[position + 1][6].equals("true")) { try { if (player != null) { player.stop(); player = new Player(play_bar, strings[position + 1][2], strings[0][position], (!strings[position + 1][4].equals("null")) ? strings[position + 1][4] : strings[position + 1][3], true); } else { player = new Player(play_bar, strings[position + 1][2], strings[0][position], (!strings[position + 1][4].equals("null")) ? strings[position + 1][4] : strings[position + 1][3], true); } } catch (IOException e) { e.printStackTrace(); } } else { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setMessage("Desculpe, no possvel reproduzir essa msica, escolha outra."); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); } } }); } listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (strings[position + 1][6].equals("true")) { File dir = new File(Environment.getExternalStorageDirectory() + "/Ducksound"); if (!dir.exists()) { dir.mkdirs(); } final DownloadManager DM = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE); String download_url; if (strings[position + 1][0].equals("true")) { download_url = strings[position + 1][5] + "?client_id=" + MainActivity.CLIENT_ID; } else { download_url = "http://188.138.17.231/~krafta/dow.php?url=" + strings[position + 1][2] + "?client_id=" + MainActivity.CLIENT_ID + "&name=" + URLEncoder.encode(strings[0][position] + "(Ducksound)"); } Uri uri = Uri.parse(download_url.replace("https://", "http://")); final DownloadManager.Request request = new DownloadManager.Request(uri); request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE) .setAllowedOverRoaming(false).setTitle(strings[0][position]) .setDestinationInExternalPublicDir("/Ducksound", strings[0][position].replace(" ", "_").replace(",", "_").replace("", "c") .replace("'", "_") + " (" + context.getResources().getString(R.string.app_name) + ").mp3"); AlertDialog.Builder download = new AlertDialog.Builder(context); download.setTitle("Baixar \"" + strings[0][position] + "\"?"); download.setMessage("Tem certeza que deseja baixar essa msica?\nEla ser salva em " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/Ducksound"); download.setPositiveButton("Baixar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { DM.enqueue(request); dialogInterface.dismiss(); } }); download.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).show(); } else { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setMessage("Desculpe, no possvel baixar essa msica, escolha outra."); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); } return true; } }); progress.hide(); }
From source file:uk.org.ngo.squeezer.service.SqueezeService.java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) private void downloadSong(@NonNull Uri url, String title, @NonNull Uri serverUrl) { if (url.equals(Uri.EMPTY)) { return;/*from w ww . ja v a 2 s . c om*/ } // If running on Gingerbread or greater use the Download Manager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadDatabase downloadDatabase = new DownloadDatabase(this); String localPath = getLocalFile(serverUrl); String tempFile = UUID.randomUUID().toString(); String credentials = mUsername + ":" + mPassword; String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); DownloadManager.Request request = new DownloadManager.Request(url).setTitle(title) .setDestinationInExternalFilesDir(this, Environment.DIRECTORY_MUSIC, tempFile) .setVisibleInDownloadsUi(false) .addRequestHeader("Authorization", "Basic " + base64EncodedCredentials); long downloadId = downloadManager.enqueue(request); Crashlytics.log("Registering new download"); Crashlytics.log("downloadId: " + downloadId); Crashlytics.log("tempFile: " + tempFile); Crashlytics.log("localPath: " + localPath); if (!downloadDatabase.registerDownload(downloadId, tempFile, localPath)) { Crashlytics.log(Log.WARN, TAG, "Could not register download entry for: " + downloadId); downloadManager.remove(downloadId); } } }
From source file:com.hughes.android.dictionary.DictionaryManagerActivity.java
private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) { String destFile;/* w ww . j a va 2 s.c o m*/ try { destFile = new File(new URL(downloadUrl).getPath()).getName(); } catch (MalformedURLException e) { throw new RuntimeException("Invalid download URL!", e); } DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); final DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus( DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING); final Cursor cursor = downloadManager.query(query); // Due to a bug, cursor is null instead of empty when // the download manager is disabled. if (cursor == null) { new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error)) .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed)) .setNeutralButton("Close", null).show(); return; } while (cursor.moveToNext()) { if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)))) break; if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)))) break; } if (!cursor.isAfterLast()) { downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID))); downloadButton.setText(getString(R.string.downloadButton, bytes / 1024.0 / 1024.0)); cursor.close(); return; } cursor.close(); Request request = new Request(Uri.parse(downloadUrl)); Log.d(LOG, "Downloading to: " + destFile); request.setTitle(destFile); File destFilePath = new File(application.getDictDir(), destFile); destFilePath.delete(); try { request.setDestinationUri(Uri.fromFile(destFilePath)); } catch (Exception e) { } try { downloadManager.enqueue(request); } catch (SecurityException e) { request = new Request(Uri.parse(downloadUrl)); request.setTitle(destFile); downloadManager.enqueue(request); } Log.w(LOG, "Download started: " + destFile); downloadButton.setText("X"); }
From source file:com.oakesville.mythling.MediaActivity.java
protected void downloadItem(final Item item) { try {// w w w . j a v a 2 s .co m final URL baseUrl = getAppSettings().getMythTvServicesBaseUrlWithCredentials(); String fileUrl = baseUrl + "/Content/GetFile?"; if (item.getStorageGroup() == null) fileUrl += "StorageGroup=None&"; else fileUrl += "StorageGroup=" + item.getStorageGroup().getName() + "&"; fileUrl += "FileName=" + URLEncoder.encode(item.getFilePath(), "UTF-8"); Uri uri = Uri.parse(fileUrl.toString()); ProxyInfo proxyInfo = MediaStreamProxy.needsAuthProxy(uri); if (proxyInfo != null) { // needs proxying to support authentication since DownloadManager doesn't support MediaStreamProxy proxy = new MediaStreamProxy(proxyInfo, AuthType.valueOf(appSettings.getMythTvServicesAuthType())); proxy.init(); proxy.start(); fileUrl = "http://" + proxy.getLocalhost().getHostAddress() + ":" + proxy.getPort() + uri.getPath(); if (uri.getQuery() != null) fileUrl += "?" + uri.getQuery(); } Log.i(TAG, "Media download URL: " + fileUrl); stopProgress(); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); Request request = new Request(Uri.parse(fileUrl)); request.setTitle(item.getOneLineTitle()); String downloadFilePath = null; try { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { File downloadDir = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); if (downloadDir.exists()) { String downloadPath = AppSettings.getExternalStorageDir() + "/"; if (getPath() != null && !getPath().isEmpty() && !getPath().equals("/")) downloadPath += getPath() + "/"; File destDir = new File(downloadDir + "/" + downloadPath); if (destDir.isDirectory() || destDir.mkdirs()) { downloadFilePath = downloadPath + item.getDownloadFilename(); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downloadFilePath); request.allowScanningByMediaScanner(); } } } } catch (IllegalStateException ex) { // store internal } catch (Exception ex) { // log, report and store internal Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(), Toast.LENGTH_LONG).show(); } long downloadId = dm.enqueue(request); registerDownloadReceiver(item, downloadId); Toast.makeText(getApplicationContext(), getString(R.string.downloading_) + item.getOneLineTitle(), Toast.LENGTH_LONG).show(); getAppData().addDownload(new Download(item.getId(), downloadId, downloadFilePath, new Date())); if (item.isRecording() && (mediaList.isMythTv28() || getAppSettings().isMythlingMediaServices())) new GetCutListTask((Recording) item, downloadId).execute(); } catch (Exception ex) { stopProgress(); Log.e(TAG, ex.getMessage(), ex); if (getAppSettings().isErrorReportingEnabled()) new Reporter(ex).send(); Toast.makeText(getApplicationContext(), getString(R.string.error_) + ex.toString(), Toast.LENGTH_LONG) .show(); } }