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.acrutiapps.browser.ui.components.CustomWebView.java

@Override
public void onAcceptDownload(DownloadItem item) {
    long id = ((DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(item);
    item.setId(id);/* w w  w. j ava  2  s  . com*/

    Controller.getInstance().getDownloadsList().add(item);

    Toast.makeText(mContext, String.format(mContext.getString(R.string.DownloadStart), item.getFileName()),
            Toast.LENGTH_SHORT).show();
}

From source file:com.renard.ocr.help.OCRLanguageActivity.java

private void updateLanguageListWithDownloadManagerStatus(OCRLanguageAdapter adapter) {
    if (adapter != null) {
        // find languages that are currently beeing 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);
        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
        while (c.moveToNext()) {
            final String title = c.getString(columnIndex);
            adapter.setDownloading(title, true);
        }/*  w  ww.  j  av a  2  s. c  o  m*/
        adapter.notifyDataSetChanged();
        c.close();
    }
}

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 {// w w w  .j  a  va 2  s.  com
        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:org.kde.kdeconnect.Plugins.SharePlugin.SharePlugin.java

@Override
public boolean onPackageReceived(NetworkPackage np) {

    try {//from ww  w. j a  va 2 s .  co  m
        if (np.hasPayload()) {

            Log.i("SharePlugin", "hasPayload");

            final InputStream input = np.getPayload();
            final long fileLength = np.getPayloadSize();
            final String originalFilename = np.getString("filename", Long.toString(System.currentTimeMillis()));

            //We need to check for already existing files only when storing in the default path.
            //User-defined paths use the new Storage Access Framework that already handles this.
            final boolean customDestination = ShareSettingsActivity.isCustomDestinationEnabled(context);
            final String defaultPath = ShareSettingsActivity.getDefaultDestinationDirectory().getAbsolutePath();
            final String filename = customDestination ? originalFilename
                    : FilesHelper.findNonExistingNameForNewFile(defaultPath, originalFilename);

            String displayName = FilesHelper.getFileNameWithoutExt(filename);
            final String mimeType = FilesHelper.getMimeTypeFromFile(filename);

            if ("*/*".equals(mimeType)) {
                displayName = filename;
            }

            final DocumentFile destinationFolderDocument = ShareSettingsActivity
                    .getDestinationDirectory(context);
            final DocumentFile destinationDocument = destinationFolderDocument.createFile(mimeType,
                    displayName);
            final OutputStream destinationOutput = context.getContentResolver()
                    .openOutputStream(destinationDocument.getUri());
            final Uri destinationUri = destinationDocument.getUri();

            final int notificationId = (int) System.currentTimeMillis();
            Resources res = context.getResources();
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setContentTitle(res.getString(R.string.incoming_file_title, device.getName()))
                    .setContentText(res.getString(R.string.incoming_file_text, filename))
                    .setTicker(res.getString(R.string.incoming_file_title, device.getName()))
                    .setSmallIcon(android.R.drawable.stat_sys_download).setAutoCancel(true).setOngoing(true)
                    .setProgress(100, 0, true);

            final NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean successful = true;
                    try {
                        byte data[] = new byte[1024];
                        long progress = 0, prevProgressPercentage = 0;
                        int count;
                        while ((count = input.read(data)) >= 0) {
                            progress += count;
                            destinationOutput.write(data, 0, count);
                            if (fileLength > 0) {
                                if (progress >= fileLength)
                                    break;
                                long progressPercentage = (progress * 100 / fileLength);
                                if (progressPercentage != prevProgressPercentage) {
                                    prevProgressPercentage = progressPercentage;
                                    builder.setProgress(100, (int) progressPercentage, false);
                                    NotificationHelper.notifyCompat(notificationManager, notificationId,
                                            builder.build());
                                }
                            }
                            //else Log.e("SharePlugin", "Infinite loop? :D");
                        }

                        destinationOutput.flush();

                    } catch (Exception e) {
                        successful = false;
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    } finally {
                        try {
                            destinationOutput.close();
                        } catch (Exception e) {
                        }
                        try {
                            input.close();
                        } catch (Exception e) {
                        }
                    }

                    try {
                        Log.i("SharePlugin", "Transfer finished: " + destinationUri.getPath());

                        //Update the notification and allow to open the file from it
                        Resources res = context.getResources();
                        String message = successful
                                ? res.getString(R.string.received_file_title, device.getName())
                                : res.getString(R.string.received_file_fail_title, device.getName());
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                                .setContentTitle(message).setTicker(message)
                                .setSmallIcon(android.R.drawable.stat_sys_download_done).setAutoCancel(true);
                        if (successful) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(destinationUri, mimeType);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                            stackBuilder.addNextIntent(intent);
                            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                                    PendingIntent.FLAG_UPDATE_CURRENT);
                            builder.setContentText(
                                    res.getString(R.string.received_file_text, destinationDocument.getName()))
                                    .setContentIntent(resultPendingIntent);
                        }
                        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                        if (prefs.getBoolean("share_notification_preference", true)) {
                            builder.setDefaults(Notification.DEFAULT_ALL);
                        }
                        NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build());

                        if (successful) {
                            if (!customDestination && Build.VERSION.SDK_INT >= 12) {
                                Log.i("SharePlugin", "Adding to downloads");
                                DownloadManager manager = (DownloadManager) context
                                        .getSystemService(Context.DOWNLOAD_SERVICE);
                                manager.addCompletedDownload(destinationUri.getLastPathSegment(),
                                        device.getName(), true, mimeType, destinationUri.getPath(), fileLength,
                                        false);
                            } else {
                                //Make sure it is added to the Android Gallery anyway
                                MediaStoreHelper.indexFile(context, destinationUri);
                            }
                        }

                    } catch (Exception e) {
                        Log.e("SharePlugin", "Receiver thread exception");
                        e.printStackTrace();
                    }
                }
            }).start();

        } else if (np.has("text")) {
            Log.i("SharePlugin", "hasText");

            String text = np.getString("text");
            if (Build.VERSION.SDK_INT >= 11) {
                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(text);
            } else {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            }
            Toast.makeText(context, R.string.shareplugin_text_saved, Toast.LENGTH_LONG).show();
        } else if (np.has("url")) {

            String url = np.getString("url");

            Log.i("SharePlugin", "hasUrl: " + url);

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            if (openUrlsDirectly) {
                context.startActivity(browserIntent);
            } else {
                Resources res = context.getResources();
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addNextIntent(browserIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);

                Notification noti = new NotificationCompat.Builder(context)
                        .setContentTitle(res.getString(R.string.received_url_title, device.getName()))
                        .setContentText(res.getString(R.string.received_url_text, url))
                        .setContentIntent(resultPendingIntent)
                        .setTicker(res.getString(R.string.received_url_title, device.getName()))
                        .setSmallIcon(R.drawable.ic_notification).setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_ALL).build();

                NotificationManager notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                NotificationHelper.notifyCompat(notificationManager, (int) System.currentTimeMillis(), noti);
            }
        } else {
            Log.e("SharePlugin", "Error: Nothing attached!");
        }

    } catch (Exception e) {
        Log.e("SharePlugin", "Exception");
        e.printStackTrace();
    }

    return true;
}

From source file:com.android.stockbrowser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;//  www.j  av  a2s .c o  m

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = "";//CookieManager.getInstance().getCookie(url, privateBrowsing);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("StockBrowser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:com.android.browser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;/*from  w w w. j a  v  a  2  s  . co  m*/

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("Browser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:com.sabaibrowser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;//from   ww w . ja v a  2s  .  c o m

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = privateBrowsing ? "" : CookieManager.getInstance().getCookie(url);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("Browser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:org.apache.cordova.backgroundDownload.BackgroundDownload.java

private void CleanUp(Download curDownload) {
    if (curDownload == null) {
        return;/*from  www .  j av a 2  s  . c  o m*/
    }

    if (curDownload.getTimerProgressUpdate() != null) {
        curDownload.getTimerProgressUpdate().cancel();
    }

    if (curDownload.getDownloadId() != DOWNLOAD_ID_UNDEFINED) {
        DownloadManager mgr = (DownloadManager) cordova.getActivity()
                .getSystemService(Context.DOWNLOAD_SERVICE);
        mgr.remove(curDownload.getDownloadId());
    }
    activDownloads.remove(curDownload.getUriString());

    if (activDownloads.size() == 0) {
        try {
            cordova.getActivity().unregisterReceiver(receiver);
        } catch (IllegalArgumentException e) {
            // this is fine, receiver was not registered
        }
    }

}

From source file:org.wso2.app.catalog.api.ApplicationManager.java

/**
 * Initiate downloading via DownloadManager API.
 *
 * @param url     - File URL./*from  w w  w .  jav  a 2s  . c  o  m*/
 * @param appName - Name of the application to be downloaded.
 */
private void downloadViaDownloadManager(String url, String appName) {
    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(false);
    // Set the title of this download, to be displayed in notifications
    // (if enabled).
    request.setTitle(resources.getString(R.string.downloader_message_title));
    // Set a description of this download, to be displayed in
    // notifications (if enabled)
    request.setDescription(resources.getString(R.string.downloader_message_description) + appName);
    // 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);
}

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();/*from  w  w w  . j ava2 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;
}