Search in sources :

Example 21 with DownloadManager

use of android.app.DownloadManager in project AndroidChromium by JackyAndroid.

the class DownloadManagerDelegate method addCompletedDownload.

/**
     * @see android.app.DownloadManager#addCompletedDownload(String, String, boolean, String,
     * String, long, boolean)
     */
protected long addCompletedDownload(String fileName, String description, String mimeType, String path, long length, String originalUrl, String referer, String downloadGuid) {
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
    boolean useSystemNotification = !notificationManager.areNotificationsEnabled();
    long downloadId = -1;
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        Class<?> c = manager.getClass();
        try {
            Class[] args = { String.class, String.class, boolean.class, String.class, String.class, long.class, boolean.class, Uri.class, Uri.class };
            Method method = c.getMethod("addCompletedDownload", args);
            Uri originalUri = Uri.parse(originalUrl);
            Uri refererUri = referer == null ? Uri.EMPTY : Uri.parse(referer);
            downloadId = (Long) method.invoke(manager, fileName, description, true, mimeType, path, length, useSystemNotification, originalUri, refererUri);
        } catch (SecurityException e) {
            Log.e(TAG, "Cannot access the needed method.");
        } catch (NoSuchMethodException e) {
            Log.e(TAG, "Cannot find the needed method.");
        } catch (InvocationTargetException e) {
            Log.e(TAG, "Error calling the needed method.");
        } catch (IllegalAccessException e) {
            Log.e(TAG, "Error accessing the needed method.");
        }
    } else {
        downloadId = manager.addCompletedDownload(fileName, description, true, mimeType, path, length, useSystemNotification);
    }
    addDownloadIdMapping(downloadId, downloadGuid);
    return downloadId;
}
Also used : NotificationManagerCompat(android.support.v4.app.NotificationManagerCompat) Method(java.lang.reflect.Method) DownloadManager(android.app.DownloadManager) Uri(android.net.Uri) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 22 with DownloadManager

use of android.app.DownloadManager in project ETSMobile-Android2 by ApplETS.

the class MoodleCourseDetailsFragment method onRequestSuccess.

@Override
public void onRequestSuccess(Object o) {
    if (o instanceof MoodleCoreCourses) {
        MoodleCoreCourses moodleCoreCourses = (MoodleCoreCourses) o;
        // create empty data
        listDataSectionName = new HashMap<HeaderText, Object[]>();
        listDataHeader = new ArrayList<HeaderText>();
        int positionSection = 0;
        for (MoodleCoreCourse coreCourse : moodleCoreCourses) {
            listMoodleLinkModules = new ArrayList<MoodleCoreModule>();
            listMoodleResourceContents = new ArrayList<MoodleModuleContent>();
            for (MoodleCoreModule coreModule : coreCourse.getModules()) {
                if (coreModule.getModname().equals("folder")) {
                    if (coreModule.getContents() != null)
                        listMoodleResourceContents.addAll(coreModule.getContents());
                } else if (coreModule.getModname().equals("url") || coreModule.getModname().equals("forum")) {
                    listMoodleLinkModules.add(coreModule);
                } else if (coreModule.getModname().equals("resource")) {
                    listMoodleResourceContents.addAll(coreModule.getContents());
                }
            }
            Object[] finalArray = ArrayUtils.addAll(listMoodleLinkModules.toArray(), listMoodleResourceContents.toArray());
            if (finalArray.length != 0)
                listDataSectionName.put(new HeaderText(coreCourse.getName(), positionSection), finalArray);
            positionSection++;
        }
        listDataHeader.addAll(listDataSectionName.keySet());
        Collections.sort(listDataHeader, new Comparator<HeaderText>() {

            @Override
            public int compare(HeaderText headerText1, HeaderText headerText2) {
                if (headerText1.getPosition() < headerText2.getPosition()) {
                    return -1;
                } else if (headerText1.getPosition() == headerText2.getPosition()) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        expandableListMoodleAdapter = new ExpandableListMoodleSectionAdapter(getActivity(), listDataHeader, listDataSectionName);
        expListView.setAdapter(expandableListMoodleAdapter);
        expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Object object = expandableListMoodleAdapter.getChild(groupPosition, childPosition);
                if (object instanceof MoodleModuleContent) {
                    MoodleModuleContent item = (MoodleModuleContent) object;
                    String url = item.getFileurl() + "&token=" + ApplicationManager.userCredentials.getMoodleToken();
                    Uri uri = Uri.parse(url);
                    DownloadManager.Request request = new DownloadManager.Request(uri);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, item.getFilename());
                    //                      r.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    MimeTypeMap mimetype = MimeTypeMap.getSingleton();
                    String extension = FilenameUtils.getExtension(item.getFilename());
                    request.setMimeType(mimetype.getMimeTypeFromExtension(extension));
                    dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
                    enqueue = dm.enqueue(request);
                    AnalyticsHelper.getInstance(getActivity()).sendActionEvent(getClass().getSimpleName(), TELECHARGE_FICHIER_MOODLE);
                }
                if (object instanceof MoodleCoreModule) {
                    MoodleCoreModule item = (MoodleCoreModule) object;
                    String url = "";
                    if (item.getModname().equals("url")) {
                        url = item.getContents().get(0).getFileurl();
                    } else {
                        url = item.getUrl();
                    }
                    AnalyticsHelper.getInstance(getActivity()).sendActionEvent(getClass().getSimpleName(), CONSULTE_PAGE_MOODLE);
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                }
                return true;
            }
        });
        super.onRequestSuccess(null);
    }
}
Also used : MimeTypeMap(android.webkit.MimeTypeMap) Uri(android.net.Uri) DownloadManager(android.app.DownloadManager) MoodleModuleContent(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleModuleContent) ExpandableListMoodleSectionAdapter(ca.etsmtl.applets.etsmobile.ui.adapter.ExpandableListMoodleSectionAdapter) ExpandableListView(android.widget.ExpandableListView) MoodleCoreModule(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCoreModule) MoodleCoreCourse(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCoreCourse) MoodleCoreCourses(ca.etsmtl.applets.etsmobile.model.Moodle.MoodleCoreCourses) SpringAndroidSpiceRequest(com.octo.android.robospice.request.springandroid.SpringAndroidSpiceRequest) Intent(android.content.Intent) View(android.view.View) ExpandableListView(android.widget.ExpandableListView)

Example 23 with DownloadManager

use of android.app.DownloadManager in project Lightning-Browser by anthonycr.

the class DownloadHandler method onDownloadStartNoStream.

/**
     * Notify the host application a download should be done, even if there is a
     * streaming viewer available for thise type.
     *
     * @param context            The context in which the download is requested.
     * @param url                The full url to the content that should be downloaded
     * @param userAgent          User agent of the downloading application.
     * @param contentDisposition Content-disposition http header, if present.
     * @param mimetype           The mimetype of the content reported by the server
     */
/* package */
private static void onDownloadStartNoStream(@NonNull final Activity context, @NonNull PreferenceManager preferences, String url, String userAgent, String contentDisposition, @Nullable String mimetype) {
    final 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;
        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = context.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = context.getString(R.string.download_no_sdcard_dlg_msg);
            title = R.string.download_no_sdcard_dlg_title;
        }
        Dialog dialog = new AlertDialog.Builder(context).setTitle(title).setIcon(android.R.drawable.ic_dialog_alert).setMessage(msg).setPositiveButton(R.string.action_ok, null).show();
        BrowserDialog.setDialogSize(context, dialog);
        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 catch the
        // exception here
        Log.e(TAG, "Exception while trying to parse url '" + url + '\'', e);
        Utils.showSnackbar(context, R.string.problem_download);
        return;
    }
    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Utils.showSnackbar(context, R.string.cannot_download);
        return;
    }
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs
    // depending on mimetype?
    String location = preferences.getDownloadDirectory();
    Uri downloadFolder;
    location = addNecessarySlashes(location);
    downloadFolder = Uri.parse(location);
    File dir = new File(downloadFolder.getPath());
    if (!dir.isDirectory() && !dir.mkdirs()) {
        // Cannot make the directory
        Utils.showSnackbar(context, R.string.problem_location_download);
        return;
    }
    if (!isWriteAccessAvailable(downloadFolder)) {
        Utils.showSnackbar(context, R.string.problem_location_download);
        return;
    }
    String newMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(Utils.guessFileExtension(filename));
    Log.d(TAG, "New mimetype: " + newMimeType);
    request.setMimeType(newMimeType);
    request.setDestinationUri(Uri.parse(Constants.FILE + location + filename));
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.setVisibleInDownloadsUi(true);
    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);
    request.addRequestHeader(COOKIE_REQUEST_HEADER, cookies);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //noinspection VariableNotUsedInsideIf
    if (mimetype == null) {
        Log.d(TAG, "Mimetype is 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(context, request, addressString, cookies, userAgent).start();
    } else {
        Log.d(TAG, "Valid mimetype, attempting to download");
        final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        try {
            manager.enqueue(request);
        } catch (IllegalArgumentException e) {
            // Probably got a bad URL or something
            Log.e(TAG, "Unable to enqueue request", e);
            Utils.showSnackbar(context, R.string.cannot_download);
        } catch (SecurityException e) {
            // TODO write a download utility that downloads files rather than rely on the system
            // because the system can only handle Environment.getExternal... as a path
            Utils.showSnackbar(context, R.string.problem_location_download);
        }
        Utils.showSnackbar(context, context.getString(R.string.download_pending) + ' ' + filename);
    }
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) Uri(android.net.Uri) DownloadManager(android.app.DownloadManager) IOException(java.io.IOException) ActivityNotFoundException(android.content.ActivityNotFoundException) Dialog(android.app.Dialog) BrowserDialog(acr.browser.lightning.dialog.BrowserDialog) AlertDialog(android.support.v7.app.AlertDialog) File(java.io.File)

Example 24 with DownloadManager

use of android.app.DownloadManager in project Lightning-Browser by anthonycr.

the class FetchUrlMimeType method run.

@Override
public void run() {
    // User agent is likely to be null, though the AndroidHttpClient
    // seems ok with that.
    String mimeType = null;
    String contentDisposition = null;
    HttpURLConnection connection = null;
    try {
        URL url = new URL(mUri);
        connection = (HttpURLConnection) url.openConnection();
        if (mCookies != null && !mCookies.isEmpty()) {
            connection.addRequestProperty("Cookie", mCookies);
            connection.setRequestProperty("User-Agent", mUserAgent);
        }
        connection.connect();
        // the server sends the right mimetype
        if (connection.getResponseCode() == 200) {
            String header = connection.getHeaderField("Content-Type");
            if (header != null) {
                mimeType = header;
                final int semicolonIndex = mimeType.indexOf(';');
                if (semicolonIndex != -1) {
                    mimeType = mimeType.substring(0, semicolonIndex);
                }
            }
            String contentDispositionHeader = connection.getHeaderField("Content-Disposition");
            if (contentDispositionHeader != null) {
                contentDisposition = contentDispositionHeader;
            }
        }
    } catch (@NonNull IllegalArgumentException | IOException ex) {
        if (connection != null)
            connection.disconnect();
    } finally {
        if (connection != null)
            connection.disconnect();
    }
    String filename = "";
    if (mimeType != null) {
        if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) {
            String newMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(Utils.guessFileExtension(mUri));
            if (newMimeType != null) {
                mRequest.setMimeType(newMimeType);
            }
        }
        filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType);
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    }
    // Start the download
    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    try {
        manager.enqueue(mRequest);
    } catch (IllegalArgumentException e) {
        // Probably got a bad URL or something
        Log.e(TAG, "Unable to enqueue request", e);
        Schedulers.main().execute(new Runnable() {

            @Override
            public void run() {
                Utils.showSnackbar(mContext, R.string.cannot_download);
            }
        });
    } catch (SecurityException e) {
        // TODO write a download utility that downloads files rather than rely on the system
        // because the system can only handle Environment.getExternal... as a path
        Schedulers.main().execute(new Runnable() {

            @Override
            public void run() {
                Utils.showSnackbar(mContext, R.string.problem_location_download);
            }
        });
    }
    final String file = filename;
    Schedulers.main().execute(new Runnable() {

        @Override
        public void run() {
            Utils.showSnackbar(mContext, mContext.getString(R.string.download_pending) + ' ' + file);
        }
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) IOException(java.io.IOException) DownloadManager(android.app.DownloadManager) URL(java.net.URL)

Example 25 with DownloadManager

use of android.app.DownloadManager in project android_frameworks_base by crdroidandroid.

the class FilesActivityUiTest method testDownload_Queued.

// We don't really need to test the entirety of download support
// since downloads is (almost) just another provider.
@Suppress
public void testDownload_Queued() throws Exception {
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    // This downloads ends up being queued (because DNS can't be resolved).
    // We'll still see an entry in the downloads UI with a "Queued" label.
    dm.enqueue(new Request(Uri.parse("http://hammychamp.toodles")));
    bots.roots.openRoot("Downloads");
    bots.directory.assertDocumentsPresent("Queued");
}
Also used : Request(android.app.DownloadManager.Request) DownloadManager(android.app.DownloadManager) Suppress(android.test.suitebuilder.annotation.Suppress)

Aggregations

DownloadManager (android.app.DownloadManager)53 File (java.io.File)14 Cursor (android.database.Cursor)13 Request (android.app.DownloadManager.Request)12 Uri (android.net.Uri)12 Suppress (android.test.suitebuilder.annotation.Suppress)10 Query (android.app.DownloadManager.Query)9 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 Intent (android.content.Intent)5 UiObject (android.support.test.uiautomator.UiObject)5 Response (com.android.volley.Response)3 Context (android.content.Context)2 Nullable (android.support.annotation.Nullable)2 AlertDialog (android.support.v7.app.AlertDialog)2 View (android.view.View)2 Request (com.android.volley.Request)2 VolleyError (com.android.volley.VolleyError)2 FileInputStream (java.io.FileInputStream)2 JSONObject (org.json.JSONObject)2