Example usage for android.content Context DOWNLOAD_SERVICE

List of usage examples for android.content Context DOWNLOAD_SERVICE

Introduction

In this page you can find the example usage for android.content Context DOWNLOAD_SERVICE.

Prototype

String DOWNLOAD_SERVICE

To view the source code for android.content Context DOWNLOAD_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.DownloadManager for requesting HTTP downloads.

Usage

From source file:com.tcity.android.ui.info.BuildArtifactsFragment.java

@Override
public void onDownloadClick(@NotNull BuildArtifact artifact) {
    //noinspection ResultOfMethodCallIgnored
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();

    DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(calculateArtifactRequest(artifact));
}

From source file:org.que.activities.fragments.PaperDetailMenuFragment.java

/**
 * @author deLaczkovich on 26.06.2014.//from  w  ww . j a v a  2  s. co  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:com.mogoweb.browser.FetchUrlMimeType.java

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
    //        HttpHost httpHost;
    //        try {
    //            httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
    //            if (httpHost != null) {
    //                ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
    //            }
    //        } catch (IllegalArgumentException ex) {
    //            Log.e(LOGTAG,"Download failed: " + ex);
    //            client.close();
    //            return;
    //        }//from  w  ww  . ja  v a 2s  .c  o m
    HttpHead request = new HttpHead(mUri);

    if (mCookies != null && mCookies.length() > 0) {
        request.addHeader("Cookie", mCookies);
    }

    HttpResponse response;
    String mimeType = null;
    String contentDisposition = null;
    try {
        response = client.execute(request);
        // We could get a redirect here, but if we do lets let
        // the download manager take care of it, and thus trust that
        // the server sends the right mimetype
        if (response.getStatusLine().getStatusCode() == 200) {
            Header header = response.getFirstHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader.getValue();
            }
        }
    } catch (IllegalArgumentException ex) {
        request.abort();
    } catch (IOException ex) {
        request.abort();
    } finally {
        client.close();
    }

    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton()
                    .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri));
            if (newMimeType != null) {
                mimeType = newMimeType;
                mRequest.setMimeType(newMimeType);
            }
        }
        String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }

    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(mRequest);
}

From source file:com.bluros.updater.service.DownloadService.java

private long enqueueDownload(String downloadUrl, String localFilePath) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
    String userAgent = Utils.getUserAgentString(this);
    if (userAgent != null) {
        request.addRequestHeader("User-Agent", userAgent);
    }/* w ww . j a  va2 s.c  o  m*/
    request.setTitle(getString(R.string.app_name));
    request.setDestinationUri(Uri.parse(localFilePath));
    request.setAllowedOverRoaming(false);
    request.setVisibleInDownloadsUi(false);

    // TODO: this could/should be made configurable
    request.setAllowedOverMetered(true);

    final DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    return dm.enqueue(request);
}

From source file:de.escoand.readdaily.DownloadHandler.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    final Database db = Database.getInstance(context);
    final Cursor downloads = db.getDownloads();

    LogHandler.log(Log.WARN, "receive starting");

    while (downloads.moveToNext()) {
        final long id = downloads.getLong(downloads.getColumnIndex(Database.COLUMN_ID));
        final String name = downloads.getString(downloads.getColumnIndex(Database.COLUMN_SUBSCRIPTION));
        final String mime = downloads.getString(downloads.getColumnIndex(Database.COLUMN_TYPE));
        final Cursor download = manager.query(new DownloadManager.Query().setFilterById(id));

        // download exists
        if (!download.moveToFirst())
            continue;

        // download finished
        if (download.getInt(
                download.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL)
            continue;

        // import file in background
        new Thread(new Runnable() {
            @Override/*from  ww w. j a  v  a 2 s. c  om*/
            public void run() {
                try {
                    LogHandler.log(Log.WARN, "import starting of " + name);

                    final FileInputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(
                            manager.openDownloadedFile(id));
                    final String mimeServer = manager.getMimeTypeForDownloadedFile(id);

                    LogHandler.log(Log.INFO, "id: " + String.valueOf(id));
                    LogHandler.log(Log.INFO, "manager: " + manager.toString());
                    LogHandler.log(Log.INFO, "stream: " + stream.toString());
                    LogHandler.log(Log.INFO, "mime: " + mime);
                    LogHandler.log(Log.INFO, "mimeServer: " + mimeServer);

                    switch (mime != null ? mime : (mimeServer != null ? mimeServer : "")) {

                    // register feedback
                    case "application/json":
                        final byte[] buf = new byte[256];
                        final int len = stream.read(buf);
                        LogHandler.log(Log.WARN, "register feedback: " + new String(buf, 0, len));
                        break;

                    // csv data
                    case "text/plain":
                        db.importCSV(name, stream);
                        break;

                    // xml data
                    case "application/xml":
                    case "text/xml":
                        db.importXML(name, stream);
                        break;

                    // zipped data
                    case "application/zip":
                        db.importZIP(name, stream);
                        break;

                    // do nothing
                    default:
                        LogHandler.log(new IntentFilter.MalformedMimeTypeException());
                        break;
                    }

                    stream.close();
                    LogHandler.log(Log.WARN, "import finished (" + name + ")");
                }

                // file error
                catch (FileNotFoundException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_open);
                }

                // stream error
                catch (IOException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_read);
                }

                // xml error
                catch (XmlPullParserException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_xml);
                }

                // clean
                finally {
                    manager.remove(id);
                    db.removeDownload(id);
                    LogHandler.log(Log.WARN, "clean finished");
                }
            }
        }).start();
    }

    downloads.close();
    LogHandler.log(Log.WARN, "receiving done");
}

From source file:org.chromium.chrome.browser.download.DownloadManagerDelegate.java

/**
 * Removes a download from Android DownloadManager.
 * @param downloadGuid The GUID of the download.
 *//*from   ww  w  .ja va  2s . c  o  m*/
void removeCompletedDownload(String downloadGuid) {
    long downloadId = removeDownloadIdMapping(downloadGuid);
    if (downloadId != INVALID_SYSTEM_DOWNLOAD_ID) {
        DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        manager.remove(downloadId);
    }
}

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   w w w.  j av a 2 s  .c om*/

    downloadManager.enqueue(request);

    showToast(mContext.getString(R.string.mytools_downloading), 1);
}

From source file:org.schabi.newpipe.DownloadDialog.java

@NonNull
@Override/*  w w  w.j  a v  a  2  s. c o  m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    arguments = getArguments();
    super.onCreateDialog(savedInstanceState);
    if (ContextCompat.checkSelfPermission(this.getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(getActivity(),
                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.download_dialog_title).setItems(R.array.download_options,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Context context = getActivity();
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                    String suffix = "";
                    String title = arguments.getString(TITLE);
                    String url = "";
                    File downloadDir = NewPipeSettings.getDownloadFolder();
                    switch (which) {
                    case 0: // Video
                        suffix = arguments.getString(FILE_SUFFIX_VIDEO);
                        url = arguments.getString(VIDEO_URL);
                        downloadDir = NewPipeSettings.getVideoDownloadFolder(context);
                        break;
                    case 1:
                        suffix = arguments.getString(FILE_SUFFIX_AUDIO);
                        url = arguments.getString(AUDIO_URL);
                        downloadDir = NewPipeSettings.getAudioDownloadFolder(context);
                        break;
                    default:
                        Log.d(TAG, "lolz");
                    }
                    if (!downloadDir.exists()) {
                        //attempt to create directory
                        boolean mkdir = downloadDir.mkdirs();
                        if (!mkdir && !downloadDir.isDirectory()) {
                            String message = context.getString(R.string.err_dir_create, downloadDir.toString());
                            Log.e(TAG, message);
                            Toast.makeText(context, message, Toast.LENGTH_LONG).show();

                            return;
                        }
                        String message = context.getString(R.string.info_dir_created, downloadDir.toString());
                        Log.e(TAG, message);
                        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                    }

                    File saveFilePath = new File(downloadDir, createFileName(title) + suffix);

                    long id = 0;
                    if (App.isUsingTor()) {
                        // if using Tor, do not use DownloadManager because the proxy cannot be set
                        Downloader.downloadFile(getContext(), url, saveFilePath, title);
                    } else {
                        DownloadManager dm = (DownloadManager) context
                                .getSystemService(Context.DOWNLOAD_SERVICE);
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                        request.setDestinationUri(Uri.fromFile(saveFilePath));
                        request.setNotificationVisibility(
                                DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                        request.setTitle(title);
                        request.setDescription("'" + url + "' => '" + saveFilePath + "'");
                        request.allowScanningByMediaScanner();

                        try {
                            id = dm.enqueue(request);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    Log.i(TAG, "Started downloading '" + url + "' => '" + saveFilePath + "' #" + id);
                }
            });
    return builder.create();
}

From source file:org.botlibre.sdk.activity.graphic.GraphicActivity.java

public void downloadFile(View v) {

    if (gInstance.fileName.equals("")) {
        MainActivity.showMessage("Missing file!", this);
        return;//from   w w w.  ja  va2  s  .  co  m
    }

    String url = MainActivity.WEBSITE + "/" + gInstance.media;

    try {

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle(gInstance.fileName);
        request.setDescription(MainActivity.WEBSITE);

        //      request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);  only download thro wifi.

        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        Toast.makeText(GraphicActivity.this, "Downloading " + gInstance.fileName, Toast.LENGTH_SHORT).show();

        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, gInstance.fileName);
        DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);

        BroadcastReceiver onComplete = new BroadcastReceiver() {
            public void onReceive(Context ctxt, Intent intent) {
                Toast.makeText(GraphicActivity.this, gInstance.fileName + " Downloaded!", Toast.LENGTH_SHORT)
                        .show();
            }
        };
        manager.enqueue(request);
        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    } catch (Exception e) {
        MainActivity.showMessage(e.getMessage(), this);
    }
}

From source file:com.otaupdater.utils.RomInfo.java

@TargetApi(11)
public long fetchFile(Context ctx) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setTitle(ctx.getString(R.string.notif_downloading));
    request.setDescription(romName);/*  ww  w. j a va2 s  .co  m*/
    request.setVisibleInDownloadsUi(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }

    request.setDestinationUri(Uri.fromFile(new File(Config.ROM_DL_PATH_FILE, getDownloadFileName())));

    int netTypes = DownloadManager.Request.NETWORK_WIFI;
    if (!Config.getInstance(ctx).getWifiOnlyDl())
        netTypes |= DownloadManager.Request.NETWORK_MOBILE;
    request.setAllowedNetworkTypes(netTypes);

    DownloadManager manager = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
    return manager.enqueue(request);
}