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.otaupdater.utils.KernelInfo.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(kernelName);/* w  w w.  jav a2s  . 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.KERNEL_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);
}

From source file:com.github.dfa.diaspora_android.ui.ContextMenuWebView.java

@Override
protected void onCreateContextMenu(ContextMenu menu) {
    super.onCreateContextMenu(menu);

    HitTestResult result = getHitTestResult();

    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            HitTestResult result = getHitTestResult();
            String url = result.getExtra();
            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                boolean writeToStoragePermitted = true;
                if (android.os.Build.VERSION.SDK_INT >= 23) {
                    int hasWRITE_EXTERNAL_STORAGE = parentActivity
                            .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                        writeToStoragePermitted = false;
                        if (!parentActivity.shouldShowRequestPermissionRationale(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                    .setPositiveButton(context.getText(android.R.string.yes),
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (android.os.Build.VERSION.SDK_INT >= 23)
                                                        parentActivity.requestPermissions(new String[] {
                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                }
                                            })
                                    .setNegativeButton(context.getText(android.R.string.no), null).show();
                        }//  w  w w  .  ja v a  2  s .  co  m
                        parentActivity.requestPermissions(
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                    }
                }
                if (writeToStoragePermitted) {
                    if (url != null) {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        File destinationFile = new File(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        request.setDestinationUri(Uri.fromFile(destinationFile));
                        ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);
                        Toast.makeText(context, context.getText(R.string.share__toast_saved_image_to_location)
                                + " " + destinationFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    }
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {
                    boolean writeToStoragePermitted = true;
                    if (android.os.Build.VERSION.SDK_INT >= 23) {
                        int hasWRITE_EXTERNAL_STORAGE = parentActivity
                                .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                            writeToStoragePermitted = false;
                            if (!parentActivity.shouldShowRequestPermissionRationale(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                        .setPositiveButton(context.getText(android.R.string.yes),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        if (android.os.Build.VERSION.SDK_INT >= 23)
                                                            parentActivity.requestPermissions(new String[] {
                                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                    MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                    }
                                                })
                                        .setNegativeButton(context.getText(android.R.string.no), null).show();
                            } else {
                                parentActivity.requestPermissions(
                                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                            }
                        }
                    }
                    if (writeToStoragePermitted) {
                        final Uri local = Uri.parse(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        new ImageDownloadTask(null, local.getPath()) {
                            @Override
                            protected void onPostExecute(Bitmap result) {
                                Uri myUri = Uri.fromFile(new File(local.getPath()));
                                Intent sharingIntent = new Intent();
                                sharingIntent.setAction(Intent.ACTION_SEND);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);
                                sharingIntent.setType("image/png");
                                sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                context.startActivity(Intent.createChooser(sharingIntent,
                                        getResources().getString(R.string.action_share_dotdotdot)));
                            }
                        }.execute(url);
                    }
                } else {
                    Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
                }

                break;

            case ID_IMAGE_EXTERNAL_BROWSER:
                if (url != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                }
                break;

            //Copy url to clipboard
            case ID_COPY_LINK:
                if (url != null) {
                    ClipboardManager clipboard = (ClipboardManager) context
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                    Toast.makeText(context, R.string.share__toast_link_address_copied, Toast.LENGTH_SHORT)
                            .show();
                }
                break;

            //Try to share link to other apps
            case ID_SHARE_LINK:
                if (url != null) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                    sendIntent.setType("text/plain");
                    context.startActivity(Intent.createChooser(sendIntent,
                            getResources().getText(R.string.context_menu_share_link)));
                }
                break;
            }
            return true;
        }
    };

    //Build context menu
    if (result.getType() == HitTestResult.IMAGE_TYPE
            || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        // Menu options for an image.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.context_menu_save_image))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0,
                context.getString(R.string.context_menu_open_external_browser))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.context_menu_share_image))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == HitTestResult.ANCHOR_TYPE
            || result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
        // Menu options for a hyperlink.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.context_menu_copy_link))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.context_menu_share_link))
                .setOnMenuItemClickListener(handler);
    }
}

From source file:com.github.dfa.diaspora_android.web.ContextMenuWebView.java

@Override
protected void onCreateContextMenu(ContextMenu menu) {
    super.onCreateContextMenu(menu);

    HitTestResult result = getHitTestResult();

    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            HitTestResult result = getHitTestResult();
            String url = result.getExtra();
            switch (item.getItemId()) {
            //Save image to external memory
            case ID_SAVE_IMAGE: {
                boolean writeToStoragePermitted = true;
                if (android.os.Build.VERSION.SDK_INT >= 23) {
                    int hasWRITE_EXTERNAL_STORAGE = parentActivity
                            .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                        writeToStoragePermitted = false;
                        if (!parentActivity.shouldShowRequestPermissionRationale(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                    .setPositiveButton(context.getText(android.R.string.yes),
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (android.os.Build.VERSION.SDK_INT >= 23)
                                                        parentActivity.requestPermissions(new String[] {
                                                                Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                }
                                            })
                                    .setNegativeButton(context.getText(android.R.string.no), null).show();
                        }/*from  w  w  w  .ja v  a2  s .c om*/
                        parentActivity.requestPermissions(
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                    }
                }
                if (writeToStoragePermitted) {
                    if (url != null) {
                        Uri source = Uri.parse(url);
                        DownloadManager.Request request = new DownloadManager.Request(source);
                        File destinationFile = new File(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        request.setDestinationUri(Uri.fromFile(destinationFile));
                        ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request);

                        Toast.makeText(context, context.getText(R.string.share__toast_saved_image_to_location)
                                + " " + destinationFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                    }
                }
            }
                break;

            case ID_SHARE_IMAGE:
                if (url != null) {
                    boolean writeToStoragePermitted = true;
                    if (android.os.Build.VERSION.SDK_INT >= 23) {
                        int hasWRITE_EXTERNAL_STORAGE = parentActivity
                                .checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        if (hasWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
                            writeToStoragePermitted = false;
                            if (!parentActivity.shouldShowRequestPermissionRationale(
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                new AlertDialog.Builder(parentActivity).setMessage(R.string.permissions_image)
                                        .setPositiveButton(context.getText(android.R.string.yes),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        if (android.os.Build.VERSION.SDK_INT >= 23)
                                                            parentActivity.requestPermissions(new String[] {
                                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                                                    MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                                                    }
                                                })
                                        .setNegativeButton(context.getText(android.R.string.no), null).show();
                            } else {
                                parentActivity.requestPermissions(
                                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                        MainActivity.REQUEST_CODE__ACCESS_EXTERNAL_STORAGE);
                            }
                        }
                    }
                    if (writeToStoragePermitted) {
                        final Uri local = Uri.parse(Environment.getExternalStorageDirectory()
                                + "/Pictures/Diaspora/" + System.currentTimeMillis() + ".png");
                        new ImageDownloadTask(null, local.getPath()) {
                            @Override
                            protected void onPostExecute(Bitmap result) {
                                Uri myUri = Uri.fromFile(new File(local.getPath()));
                                Intent sharingIntent = new Intent();
                                sharingIntent.setAction(Intent.ACTION_SEND);
                                sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);
                                sharingIntent.setType("image/png");
                                sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                context.startActivity(Intent.createChooser(sharingIntent,
                                        getResources().getString(R.string.action_share_dotdotdot)));
                            }
                        }.execute(url);
                    }
                } else {
                    Toast.makeText(context, "Cannot share image: url is null", Toast.LENGTH_SHORT).show();
                }

                break;

            case ID_IMAGE_EXTERNAL_BROWSER:
                if (url != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                }
                break;

            //Copy url to clipboard
            case ID_COPY_LINK:
                if (url != null) {
                    ClipboardManager clipboard = (ClipboardManager) context
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                    Toast.makeText(context, R.string.share__toast_link_address_copied, Toast.LENGTH_SHORT)
                            .show();
                }
                break;

            //Try to share link to other apps
            case ID_SHARE_LINK:
                if (url != null) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                    sendIntent.setType("text/plain");
                    context.startActivity(Intent.createChooser(sendIntent,
                            getResources().getText(R.string.context_menu_share_link)));
                }
                break;
            }
            return true;
        }
    };

    //Build context menu
    if (result.getType() == HitTestResult.IMAGE_TYPE
            || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        // Menu options for an image.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_SAVE_IMAGE, 0, context.getString(R.string.context_menu_save_image))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_IMAGE_EXTERNAL_BROWSER, 0,
                context.getString(R.string.context_menu_open_external_browser))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_IMAGE, 0, context.getString(R.string.context_menu_share_image))
                .setOnMenuItemClickListener(handler);
    } else if (result.getType() == HitTestResult.ANCHOR_TYPE
            || result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
        // Menu options for a hyperlink.
        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_COPY_LINK, 0, context.getString(R.string.context_menu_copy_link))
                .setOnMenuItemClickListener(handler);
        menu.add(0, ID_SHARE_LINK, 0, context.getString(R.string.context_menu_share_link))
                .setOnMenuItemClickListener(handler);
    }
}

From source file:com.cuddlesoft.nori.fragment.ImageFragment.java

/**
 * Use the system {@link android.app.DownloadManager} service to download the image.
 *//*w  w w.  j  ava 2  s. co m*/
protected void downloadImage() {
    // Get download manager system service.
    DownloadManager downloadManager = (DownloadManager) getActivity()
            .getSystemService(Context.DOWNLOAD_SERVICE);

    // Extract file name from URL.
    String fileName = image.fileUrl.substring(image.fileUrl.lastIndexOf("/") + 1);
    // Create download directory, if it does not already exist.
    //noinspection ResultOfMethodCallIgnored
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();

    // Create and queue download request.
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(image.fileUrl)).setTitle(fileName)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
            .setVisibleInDownloadsUi(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Trigger media scanner to add image to system gallery app on Honeycomb and above.
        request.allowScanningByMediaScanner();
        // Show download UI notification on Honeycomb and above.
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    downloadManager.enqueue(request);
}

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   ww  w.  ja  v  a 2 s .  c o 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: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 a2 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:com.fairphone.updater.UpdaterService.java

private void setupDownloadManager() {
    mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

    mDownloadBroadCastReceiver = new DownloadBroadCastReceiver();

    getApplicationContext().registerReceiver(mDownloadBroadCastReceiver,
            new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

From source file:com.example.linhdq.test.main_menu.language.OCRLanguageActivity.java

private void updateLanguageListWithDownloadManagerStatus(OCRLanguageAdapter adapter) {
    if (adapter != null) {
        // find languages that are currently being downloaded
        Query query = new Query();
        query.setFilterByStatus(DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING
                | DownloadManager.STATUS_PAUSED);
        final DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor c = dm.query(query);
        if (c == null) {
            return;
        }//  w w w .  j a va2  s  .c  om
        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
        while (c.moveToNext()) {
            final String title = c.getString(columnIndex);
            adapter.setDownloading(title, true);
        }
        adapter.notifyDataSetChanged();
        c.close();
    }
}

From source file:org.catrobat.catroid.ui.WebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);

    ActionBar actionBar = getActionBar();
    actionBar.hide();/*w  ww. j  a  v a 2 s.  co m*/

    Intent intent = getIntent();
    url = intent.getStringExtra(INTENT_PARAMETER_URL);
    if (url == null) {
        url = Constants.BASE_URL_HTTPS;
    }
    callingActivity = intent.getStringExtra(CALLING_ACTIVITY);

    webView = (WebView) findViewById(R.id.webView);
    webView.setBackgroundColor(
            ResourcesCompat.getColor(getResources(), R.color.application_background_color, null));
    webView.setWebViewClient(new MyWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    String language = String.valueOf(Constants.CURRENT_CATROBAT_LANGUAGE_VERSION);
    String flavor = Constants.FLAVOR_DEFAULT;
    String version = Utils.getVersionName(getApplicationContext());
    String platform = Constants.PLATFORM_DEFAULT;
    webView.getSettings().setUserAgentString(
            "Catrobat/" + language + " " + flavor + "/" + version + " Platform/" + platform);

    webView.loadUrl(url);

    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Log.d(WebViewActivity.class.getSimpleName(),
                    "contentDisposition: " + contentDisposition + "   " + mimetype);

            if (getExtensionFromContentDisposition(contentDisposition).contains(Constants.CATROBAT_EXTENSION)) {
                DownloadUtil.getInstance().prepareDownloadAndStartIfPossible(WebViewActivity.this, url);
            } else if (url.contains(Constants.LIBRARY_BASE_URL)) {
                String name = getMediaNameFromUrl(url);
                String mediaType = getMediaTypeFromContentDisposition(contentDisposition);
                String fileName = name + getExtensionFromContentDisposition(contentDisposition);
                String tempPath = null;
                switch (mediaType) {
                case Constants.MEDIA_TYPE_LOOK:
                    tempPath = Constants.TMP_LOOKS_PATH;
                    break;
                case Constants.MEDIA_TYPE_SOUND:
                    tempPath = Constants.TMP_SOUNDS_PATH;
                }
                String filePath = Utils.buildPath(tempPath, fileName);
                resultIntent.putExtra(MEDIA_FILE_PATH, filePath);
                DownloadUtil.getInstance().prepareMediaDownloadAndStartIfPossible(WebViewActivity.this, url,
                        mediaType, name, filePath, callingActivity);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setTitle(getString(R.string.notification_download_title_pending) + " "
                        + DownloadUtil.getInstance().getProjectNameFromUrl(url));
                request.setDescription(getString(R.string.notification_download_pending));
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                        DownloadUtil.getInstance().getProjectNameFromUrl(url) + ANDROID_APPLICATION_EXTENSION);
                request.setMimeType(mimetype);

                registerReceiver(onDownloadComplete,
                        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                downloadManager.enqueue(request);
            }
        }
    });
}

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));
    }//w  w w . ja v  a 2  s  .co  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);
}