private void download(String url) {
    try {
      mFile =
          FileUtil.getDestinationInExternalPublicDir(
              getFileDownloadPath(), mFileObject.getSaveName(mProjectObjectId));

      PersistentCookieStore cookieStore =
          new PersistentCookieStore(AttachmentsDownloadDetailActivity.this);
      String cookieString = "";
      for (Cookie cookie : cookieStore.getCookies()) {
        cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
      }

      DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
      request.addRequestHeader("Cookie", cookieString);
      request.setDestinationInExternalPublicDir(
          getFileDownloadPath(), mFileObject.getSaveName(mProjectObjectId));
      request.setTitle(mFileObject.getName());
      // request.setDescription(mFileObject.name);
      // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
      request.setVisibleInDownloadsUi(false);
      // request.allowScanningByMediaScanner();
      // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
      // request.setShowRunningNotification(false);

      downloadId = downloadManager.enqueue(request);
      downloadListEditor.putLong(mFileObject.file_id, downloadId);
      downloadListEditor.commit();
    } catch (Exception e) {
      Toast.makeText(this, R.string.no_system_download_service, Toast.LENGTH_LONG).show();
    }
  }
  /**
   * 下载一个文件
   *
   * @param dirType
   * @param subPath
   * @param url
   * @return
   */
  public long downLoadFile(String dirType, String subPath, final String url, boolean isExternal) {

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    /** 设置用于下载时的网络状态 */
    request.setAllowedNetworkTypes(
        DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    /** 设置通知栏是否可见 */
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
    /** 设置漫游状态下是否可以下载 */
    request.setAllowedOverRoaming(false);
    /** 如果我们希望下载的文件可以被系统的Downloads应用扫描到并管理, 我们需要调用Request对象的setVisibleInDownloadsUi方法,传递参数true. */
    request.setVisibleInDownloadsUi(true);
    /** 设置文件保存路径 */
    if (isExternal) {
      request.setDestinationInExternalPublicDir(dirType, subPath);
    } else {
      request.setDestinationInExternalFilesDir(context, dirType, subPath);
    }
    /** 将下载请求放入队列, return下载任务的ID */
    long downloadId = downloadManager.enqueue(request);

    Log.d(TAG, "下载Id:" + downloadId);

    // 在执行下载前注册内容监听者
    context
        .getContentResolver()
        .registerContentObserver(
            Uri.parse("content://downloads/"),
            true,
            DownloadManagerObserver.newInstance(
                new Handler(), context, DownloadUtilObserver.newInstance()));
    return downloadId;
  }
Exemple #3
1
 /**
  * Download a file using Android download manager.
  *
  * @param url URL to download
  * @param fileName Destination file name
  * @param title Notification title
  * @param description Notification description
  */
 public static void downloadFile(
     Context context, String url, String fileName, String title, String description) {
   String authToken = PreferenceUtil.getAuthToken(context);
   DownloadManager downloadManager =
       (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
   DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
   request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
   request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
   request.addRequestHeader("Cookie", "auth_token=" + authToken);
   request.setTitle(title);
   request.setDescription(description);
   downloadManager.enqueue(request);
 }
 @SuppressLint("NewApi")
 public static void download(
     Context context, String url, String savedFileName, String title, String desc) {
   DownloadManager downloadManager =
       (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
   String apkUrl =
       url; // "http://img.meilishuo.net/css/images/AndroidShare/Meilishuo_3.6.1_10006.apk";
   DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
   request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, savedFileName);
   request.setTitle(title);
   request.setDescription(desc); // "餐厅管家,绿色免费"
   // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
   request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
   // request.setMimeType("application/com.trinea.download.file");
   long downloadId = downloadManager.enqueue(request);
 }
 @SuppressLint("NewApi")
 public void download(VersionInfo version) {
   initDownload();
   AppLog.out(TAG, "更新地址:" + HttpUrl.OSS + version.getSourceUrl(), AppLog.LEVEL_INFO);
   DownloadManager.Request request =
       new DownloadManager.Request(Uri.parse(HttpUrl.OSS + version.getSourceUrl()));
   request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, version.getVersionName());
   request.setTitle(version.getVersionName());
   request.setDescription(getString(R.string.app_name));
   request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
   request.setVisibleInDownloadsUi(false);
   //        request.setMimeType(MMIMETYPE);
   downloadId = downloadManager.enqueue(request);
   /** save download id to preferences * */
   PreferencesUtils.putLong(getBaseContext(), KEY_NAME_DOWNLOAD_ID, downloadId);
   //        finish();
 }
  public void enqueueFile(Uri fileUri) {
    String scheme = fileUri.getScheme();
    if (!"http".equals(scheme) && !"https".equals(scheme)) {
      Log.w(TAG, String.format("Ignoring not HTTP/HTTPS uri: %s", fileUri));
      return;
    }

    DownloadManager.Request request = new DownloadManager.Request(fileUri);
    String localFileName = fileUri.getLastPathSegment();
    request.setDescription(String.format("Downloading file %s...", localFileName));
    request.setTitle(localFileName);
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, localFileName);

    downloadManager.enqueue(request);
  }
    protected void doDownload(String url, String filename) {
      // String url = "url you want to download";
      DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
      request.setDescription(filename);
      request.setTitle("Stream Downloader");

      // in order for this if to run, you must use the android 3.2 to compile your app
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(
            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
      }
      request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);

      // get download service and enqueue file
      DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
      manager.enqueue(request);
    }
Exemple #8
1
  public static long requestDownload(Context context, String url) {
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle(uri.getLastPathSegment());
    request.setDescription(context.getString(R.string.app_name));
    request.setVisibleInDownloadsUi(true);

    // in order for this if to run, you must use the android 3.2 to compile your app
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      request.allowScanningByMediaScanner();
      request.setNotificationVisibility(
          DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(
        Environment.DIRECTORY_DOWNLOADS, uri.getLastPathSegment());

    // get download service and enqueue file
    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    return manager.enqueue(request);
  }
 @SuppressLint("NewApi")
 private void startDownload() {
   downloadId = PreferencesUtils.getLong(mContext, DOWNLOAD_KEY, DEFAULT_DOWNLOAD_ID);
   if (downloadId == DEFAULT_DOWNLOAD_ID) {
     DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
     // 获取apk名称
     String apkName =
         mContext.getApplicationInfo().loadLabel(mContext.getPackageManager()).toString();
     // 设置下载地址
     request.setDestinationInExternalPublicDir(
         Constants.UPDATE_FILE_DIR, Constants.UPDATE_FILE_NAME);
     request.setTitle(apkName);
     request.setDescription("正在下载...");
     // 提示一直显示,下载完成后点击则消失
     request.setNotificationVisibility(
         DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
     request.setVisibleInDownloadsUi(false);
     // 加入下载队列
     downloadId = mDownloadManager.enqueue(request);
     PreferencesUtils.putLong(mContext, DOWNLOAD_KEY, downloadId);
   }
 }
  @RequiresPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
  public static long DownloadApkWithProgress(Context context, String url) {

    DownloadManager downloadManager =
        (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDestinationInExternalPublicDir("/appupdate", "update.apk");
    request.setTitle("Updating: " + context.getPackageName());
    request.setMimeType(MINETYPE_APPLCATION);
    long downloadId = 0;
    // fix crash on SecurityException.
    try {
      downloadId = downloadManager.enqueue(request);
      // this register may cause memory leak if installation failed.
      context.registerReceiver(
          new DownloadCompleteReceiver(),
          new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    } catch (SecurityException e) {
      Toast.makeText(context, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    return downloadId;
  }
  /**
   * Start download.
   *
   * @param productName the product name
   * @param url the url
   */
  public void startDownload(String productName, String url) {

    try {
      this.productName = productName;
      String fileName = url.substring(url.lastIndexOf('/') + 1);
      // URLUtil.guessFileName(url, null, null)
      Uri uri = Uri.parse(url);
      DownloadManager.Request request = new DownloadManager.Request(uri);
      request
          .setTitle(context.getString(R.string.eo_dataset) + fileName)
          .setDescription(String.format(context.getString(R.string.file_is_downloading), fileName));
      request.setDestinationInExternalPublicDir(
          getRelativePath(Const.SMARTHMA_PATH_EO_DATA), getSubPath(productName, fileName, 1));
      request.setVisibleInDownloadsUi(true);
      request.setNotificationVisibility(
          DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
      request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
      myDownloadReference = downloadManager.enqueue(request);
      Log.i("DOWNLOAD", String.valueOf(myDownloadReference));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #12
1
  public static long requestDownload(Context context, SermonItem item) {
    Uri downloadUri = Uri.parse(Const.BASE_URL + item.audioUrl);
    DownloadManager.Request request = new DownloadManager.Request(downloadUri);
    request.setTitle("설교 다운로드");
    request.setDescription(item.titleWithDate);
    request.setDestinationInExternalPublicDir(
        Environment.DIRECTORY_DOWNLOADS, item.titleWithDate + StringUtils.FILE_EXTENSION_MP3);
    //        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
    //            request.setShowRunningNotification(true);
    //        } else {
    //
    // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //        }

    DownloadManager downloadManager =
        (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    long downloadQueryId = downloadManager.enqueue(request);
    int res =
        DBManager.getInstance(context)
            .updateSermonDownloadStatus(
                item._id, downloadQueryId, SermonItem.DownloadStatus.DOWNLOAD_START);
    Logger.i(TAG, "update current item's download status result : " + res);
    return downloadQueryId;
  }
  @SuppressLint("NewApi")
  private static void downloadMedia(Object sourceButton, Object mMedia) {
    Field contextField =
        XposedHelpers.findFirstFieldByExactType(sourceButton.getClass(), Context.class);
    if (mContext == null) {
      try {
        mContext = (Context) contextField.get(sourceButton);
      } catch (Exception e) {
        e.printStackTrace();
        log("Failed to get Context");
        return;
      }
    }

    log("Downloading media...");
    Object mMediaType = getObjectField(mMedia, "b");

    Field[] mMediaFields = mMedia.getClass().getDeclaredFields();
    for (Field iField : mMediaFields) {
      String fieldType = iField.getClass().getName();
      if (fieldType.contains("com.instagram.model") && !fieldType.contains("people")) {
        try {
          mMediaType = iField.get(mMedia);
        } catch (Exception e) {
          log("Failed to get MediaType class");
          Toast.makeText(
                  mContext,
                  ResourceHelper.getString(mContext, R.string.mediatype_error),
                  Toast.LENGTH_LONG)
              .show();
          e.printStackTrace();
          return;
        }
      }
    }

    Object videoType = getStaticObjectField(mMediaType.getClass(), "b");

    String linkToDownload;
    String filenameExtension;
    String descriptionType;
    int descriptionTypeId = R.string.photo;
    if (mMediaType.equals(videoType)) {
      linkToDownload = (String) getObjectField(mMedia, "E");
      filenameExtension = "mp4";
      descriptionType = "video";
      descriptionTypeId = R.string.video;
    } else {
      linkToDownload = (String) getObjectField(mMedia, "s");
      filenameExtension = "jpg";
      descriptionType = "photo";
      descriptionTypeId = R.string.photo;
    }

    // Construct filename
    // username_imageId.jpg
    descriptionType = ResourceHelper.getString(mContext, descriptionTypeId);
    String toastMessage = ResourceHelper.getString(mContext, R.string.downloading, descriptionType);
    Toast.makeText(mContext, toastMessage, Toast.LENGTH_SHORT).show();
    Object mUser = getObjectField(mMedia, "p");
    String userName = (String) getObjectField(mUser, "b");
    String userFullName = (String) getObjectField(mUser, "c");
    String itemId = (String) getObjectField(mMedia, "t");
    String fileName = userName + "_" + itemId + "." + filenameExtension;

    if (TextUtils.isEmpty(userFullName)) {
      userFullName = userName;
    }

    File directory =
        new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getAbsolutePath()
                + "/Instagram");
    if (!directory.exists()) directory.mkdirs();

    String notificationTitle =
        ResourceHelper.getString(mContext, R.string.username_thing, userFullName, descriptionType);
    String description =
        ResourceHelper.getString(mContext, R.string.instagram_item, descriptionType);

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(linkToDownload));
    request.setTitle(notificationTitle);
    request.setDescription(description);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
      request.allowScanningByMediaScanner();
      request.setNotificationVisibility(
          DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(
        Environment.DIRECTORY_DOWNLOADS, "Instagram/" + fileName);

    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
  }
  @Override
  public void onCourseModuleSelected(final CourseModule module) {
    List<ModuleContent> contents = module.getContents();
    ModuleContent content = new ModuleContent();

    if (!contents.isEmpty()) {
      content = contents.get(0);
    }

    if ("resource".equalsIgnoreCase(module.getModname())) {

      /**
       * Files are stored in the folder /Ourvle/courses/Modified Course Name-COurse Id/files/ The
       * modified course name removes any uneccesary whitespace from the name along with some course
       * names may contain the colon The colon is a reserved character in the android library and
       * causes an illegal state exception when explicitly creating a file with that in the name
       *
       * <p>The android reserved characters for file names are {"|", "\\", "?", "*", "<", "\"", ":",
       * ">"};
       */
      String folderLocation =
          "/OurVLE/courses/"
              + mCourse.getShortname().trim().replaceAll(":", "-")
              + "-"
              + mCourse.getId()
              + "/files/"; // sub-folder definition

      File location = new File(Environment.getExternalStorageDirectory(), folderLocation);

      if (!location.exists()) {
        if (!location.mkdirs())
          Toast.makeText(this, "Error making directory to store file", Toast.LENGTH_LONG)
              .show(); // makes the subfolder
      }

      String fileLocation = location + "/" + content.getFilename();
      courseFile = new File(fileLocation);

      if (!courseFile.exists()) // checks if the file is not already present
      {
        Toast.makeText(
                getApplicationContext(), "Downloading File: " + module.getName(), Toast.LENGTH_LONG)
            .show();
        String token = SiteInfo.listAll(SiteInfo.class).get(0).getToken();
        final String url = content.getFileurl() + "&token=" + token;
        final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

        request.setDescription("Course file download");
        request.setTitle(module.getName());
        // in order for this if to run, you must use the android 3.2 to compile your app
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
          request.allowScanningByMediaScanner();
          request.setNotificationVisibility(
              DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }
        request.setDestinationInExternalPublicDir(folderLocation, content.getFilename());

        // get download service and enqueue file
        final DownloadManager manager =
            (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);

        // registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
      } else // open the file that is already present
      {
        openFile(courseFile);
      }
    } else if (module.getUrl() != null) {

      String url = module.getUrl();

      if (!url.startsWith("http://") && !url.startsWith("https://")) url = "http://" + url;

      url += ("?wstoken=" + siteInfo.getToken());

      Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
      startActivity(browserIntent);
    } else //noinspection StatementWithEmptyBody
    if ("label".equalsIgnoreCase(module.getModname())) {
      // do nothing
    } else {
      Log.d("resource", "invalid");
      Toast.makeText(
              getApplicationContext(),
              "This resource is not yet supported by OurVLE Mobile",
              Toast.LENGTH_SHORT)
          .show();
    }
  }
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // TODO Auto-generated method stub
    Uri uri =
        Uri.parse(
            moeapk.ApkDownloadUrl(
                app_package,
                moeapk.current_apklist_vcode[position],
                moeapk.current_apklist_special[position]));
    // Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    // startActivity(intent);

    DownloadManager mgr = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setDestinationInExternalPublicDir(
        "MoeApk",
        moeapk.current_apklist_appname[position]
            + "_"
            + moeapk.current_apklist_vname[position]
            + "_"
            + moeapk.current_apklist_sname[position]
            + ".apk");
    request.setAllowedNetworkTypes(
        DownloadManager.Request.NETWORK_MOBILE
            | DownloadManager.Request.NETWORK_WIFI); // 允许流量和wifi使用
    request.setAllowedOverRoaming(false); // 不允许在漫游时下载
    request.setMimeType("application/vnd.android.package-archive");
    request.setTitle(moeapk.current_apklist_appname[position]);
    request.setDescription("来自萌萌安卓的下载");
    request.setVisibleInDownloadsUi(true);
    long downloadid = mgr.enqueue(request);
    Toast.makeText(
            getApplicationContext(), "文件将保存在" + fileUtils.SDCARD + "MoeApk下", Toast.LENGTH_LONG)
        .show();
  }
  public long downLoadFile(String httpUrl, String dir, String fileName) {
    mDir = dir;
    mFileName = fileName;

    File filePath = new File(dir);
    if (!filePath.exists()) {
      filePath.mkdirs();
    }

    File file = new File(dir + "/" + fileName);
    if (file.exists()) file.delete();

    DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(httpUrl));
    request.setDestinationInExternalPublicDir(dir, fileName);

    request.setTitle("setTitle");
    request.setDescription("setDescription");

    /*android.permission.DOWNLOAD_WITHOUT_NOTIFICATION*/
    //
    // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    //        request.setMimeType("application/cn.trinea.download.file");
    register(mContext);
    return manager.enqueue(request);
  }
 private void createRequest() {
   Uri uri = Uri.parse("http://www.inf.ufpr.br/vignatti/grade_2015-2-v1.pdf");
   mRequest = new DownloadManager.Request(uri);
   mRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
   mRequest.setTitle("Grade BCC UFPR");
   mRequest.setDescription("Arquivo: grade_2015-2-v1.pdf");
   mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "grade_2015.pdf");
 }