public static void startDownload(
      Context context, Magazine magazine, boolean isTemp, String tempUrlKey) {
    String fileUrl = magazine.getItemUrl();
    String filePath = magazine.getItemPath();
    if (magazine.isSample()) {
      fileUrl = magazine.getSamplePdfUrl();
      filePath = magazine.getSamplePdfPath();
    } else if (isTemp) {
      fileUrl = tempUrlKey;
    }
    Log.d(
        TAG,
        "isSample: " + magazine.isSample() + "\nfileUrl: " + fileUrl + "\nfilePath: " + filePath);
    EasyTracker.getTracker().sendView("Downloading/" + FilenameUtils.getBaseName(filePath));
    DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl));
    request
        .setVisibleInDownloadsUi(false)
        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
        .setDescription(magazine.getSubtitle())
        .setTitle(magazine.getTitle() + (magazine.isSample() ? " Sample" : ""))
        .setDestinationInExternalFilesDir(context, null, FilenameUtils.getName(filePath));
    // TODO should use cache directory?
    magazine.setDownloadManagerId(dm.enqueue(request));

    MagazineManager magazineManager = new MagazineManager(context);
    magazineManager.removeDownloadedMagazine(context, magazine);
    magazineManager.addMagazine(magazine, Magazine.TABLE_DOWNLOADED_MAGAZINES, true);
    magazine.clearMagazineDir();
    EventBus.getDefault().post(new LoadPlistEvent());
  }
 public void updateIitc(final String url) {
   final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
   request.setDescription(getString(R.string.download_description));
   request.setTitle("IITCm Update");
   request.allowScanningByMediaScanner();
   final Uri fileUri =
       Uri.parse("file://" + getExternalFilesDir(null).toString() + "/iitcUpdate.apk");
   request.setDestinationUri(fileUri);
   // remove old update file...we don't want to spam the external storage
   deleteUpdateFile();
   // get download service and enqueue file
   final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
   manager.enqueue(request);
 }
  public void download(String url, String fileName) {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
      Uri uri = Uri.parse(url);

      DownloadManager.Request r = new DownloadManager.Request(uri);
      r.setAllowedNetworkTypes(Request.NETWORK_WIFI);
      r.setAllowedOverRoaming(false);

      // set mime type
      MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
      String mimeType =
          mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
      r.setMimeType(mimeType);

      // set in notification
      r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
      r.setVisibleInDownloadsUi(true);

      // sdcard
      if (TextUtils.isEmpty(fileName)) fileName = uri.getLastPathSegment();
      r.setDestinationInExternalFilesDir(mContext, File.separator, fileName);
      r.setTitle(fileName);

      // start download
      mDownloadId = mDM.enqueue(r);
    } else if (mListener != null) {
      SystemClock.sleep(1000);
      mListener.onDownloadComplete(null);
    }
  }
Esempio n. 4
1
  /** @param path the absolute destination path */
  static long enqueue(DownloadManager dm, String uri, String path) {
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri));

    /* Unfortunately, we cannot use the simpler "ExternalPublicDir"
    Android feature, because on some Samsung products, we need to
    explicitly use the "external_sd" mount instead of the built-in
    storage.  Here, we must use whatever was returned by
    FindDataPath() in LocalPath.cpp. */
    // request.setDestinationInExternalPublicDir("XCSoarData", path);
    request.setDestinationUri(Uri.fromFile(new File(path)));

    request.setAllowedOverRoaming(false);
    request.setShowRunningNotification(true);
    return dm.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);
 }
Esempio n. 6
1
  /**
   * 下载一个文件
   *
   * @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;
  }
  private void downloadApk(VersionInfo info) {
    Log.d(TAG, "download apk:" + info.url);
    DownloadManager downloadManager;
    downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);

    Uri uri = Uri.parse(info.url);
    DownloadManager.Request request = new Request(uri);
    File downloadDir = new File(mDownloadPath);
    if (!downloadDir.exists()) {
      downloadDir.mkdirs();
    }

    request.setTitle(mContext.getString(R.string.app_name));
    request.setDescription(info.versionName);
    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
    request.setDestinationUri(Uri.fromFile(new File(mDownloadPath, info.versionCode + ".apk")));
    mDownloadReference = downloadManager.enqueue(request);
    IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    mContext.registerReceiver(mReceiver, filter);
  }
Esempio n. 8
1
  public void StartDownload(String title, String url) {

    File mydownload =
        new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                + "/Millenials");

    if (!mydownload.exists()) {
      mydownload.mkdir();
    }

    dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request
        .setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
        .setAllowedOverRoaming(false)
        .setTitle("Millenials")
        .setDestinationInExternalPublicDir("/Millenials", title.concat(".mp3"));
    enqueue = dm.enqueue(request);
  }
  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();
    }
  }
Esempio n. 10
1
  @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;
  }
Esempio n. 11
1
  /** 初始化下载器 * */
  private void initDownManager(Intent intent) {
    mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    mCompleteReceiver = new DownloadCompletedReceiver();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String downName = intent.getStringExtra(DL_NAME);
    if (downName == null || downName.trim().equals("")) {
      throw new NullPointerException("downName---------下载名称不能为空");
    }
    String downUrl = intent.getStringExtra(DL_URL);
    if (downUrl == null || downUrl.trim().equals("")) {
      throw new NullPointerException("downUrl---------下载地址不能为空");
    }

    if (!prefs.getString(DL_NAME, "").equals(downName)) {
      // 设置下载地址
      DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));
      // 设置允许使用的网络类型,这里是移动网络和wifi都可以
      request.setAllowedNetworkTypes(
          DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
      // 下载时,通知栏显示途中
      request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
      request.setVisibleInDownloadsUi(true);
      // 设置下载后文件存放的位置
      request.setDestinationInExternalFilesDir(
          this, Environment.DIRECTORY_DOWNLOADS, "baidumusic.apk");
      // 将下载请求放入队列
      long id = mDownloadManager.enqueue(request);
      // 保存id
      prefs.edit().putLong(DL_ID, id).apply();
      prefs.edit().putString(DL_NAME, downName).commit();
    } else {
      // 下载已经开始,检查状态
      queryDownloadStatus();
    }
    // 注册下载广播
    registerReceiver(mCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  }
Esempio n. 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;
  }
Esempio n. 13
1
  private static void enqueueDownload(
      Context context,
      Uri uri,
      Uri destinationUri,
      String description,
      String mimeType,
      String mediaType,
      boolean wifiOnly) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      final DownloadManager dm =
          (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
      DownloadManager.Request request = new DownloadManager.Request(uri);

      request.setDestinationUri(destinationUri);
      request.setDescription(description);
      if (mediaType != null) {
        request.addRequestHeader("Accept", mediaType);
      }
      if (mimeType != null) {
        request.setMimeType(mimeType);
      }
      if (wifiOnly) {
        restrictDownloadToWifi(request);
      }
      request.setAllowedOverRoaming(false);

      dm.enqueue(request);
    } else {
      // HACK alert:
      // Gingerbread's DownloadManager needlessly rejected HTTPS URIs. Circumvent that
      // by building and enqueing the request to the provider by ourselves. This is safe
      // as we only rely on internal API that won't change anymore.
      ContentValues values = new ContentValues();
      values.put("uri", uri.toString());
      values.put("is_public_api", true);
      values.put("notificationpackage", context.getPackageName());
      values.put("destination", 4);
      values.put("hint", destinationUri.toString());
      if (mediaType != null) {
        values.put("http_header_0", "Accept:" + mediaType);
      }
      values.put("description", description);
      if (mimeType != null) {
        values.put("mimetype", mimeType);
      }
      values.put("visibility", 0);
      values.put("allowed_network_types", wifiOnly ? DownloadManager.Request.NETWORK_WIFI : ~0);
      values.put("allow_roaming", false);
      values.put("is_visible_in_downloads_ui", true);

      context.getContentResolver().insert(Uri.parse("content://downloads/my_downloads"), values);
    }
  }
Esempio n. 14
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);
 }
Esempio n. 15
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);
  }
Esempio n. 16
1
 @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();
 }
Esempio n. 17
1
  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);
  }
Esempio n. 18
1
    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);
    }
 @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);
   }
 }
Esempio n. 20
1
  /**
   * 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();
    }
  }
  @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();
    }
  }
Esempio n. 23
1
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //    overridePendingTransition(R.anim.fadeinanimation, 0);
    setContentView(R.layout.activity_main);

    Backendless.setUrl(Defaults.SERVER_URL);
    Backendless.initApp(this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION);

    mainScreen = findViewById(R.id.mainscreen);

    mlbbutton = findViewById(R.id.button1);
    nflbutton = findViewById(R.id.button2);
    nhlbutton = findViewById(R.id.button3);
    nbabutton = findViewById(R.id.button4);
    cfbbutton = findViewById(R.id.button5);
    cbbbutton = findViewById(R.id.button6);
    olybutton = findViewById(R.id.button7);

    //    String uri =
    // "https://api.backendless.com/B40D13D5-E84B-F009-FF57-3871FCA5AE00/v1/files/sportsreflinks.db";

    android.support.v7.app.ActionBar bar = getSupportActionBar();

    if (bar != null) {
      bar.setTitle("Sports Reference");
    }

    //  detector = new GestureDetector(this);

    prefs =
        this.getSharedPreferences("comapps.com.thenewsportsreference.app", Context.MODE_PRIVATE);

    boolean hasVisited = prefs.getBoolean("HAS_VISISTED_BEFORE", false);

    if (!hasVisited) {

      mlbbutton.setVisibility(View.INVISIBLE);
      nhlbutton.setVisibility(View.INVISIBLE);
      nbabutton.setVisibility(View.INVISIBLE);
      nflbutton.setVisibility(View.INVISIBLE);
      cfbbutton.setVisibility(View.INVISIBLE);
      cbbbutton.setVisibility(View.INVISIBLE);
      olybutton.setVisibility(View.INVISIBLE);

      /* //    Toast instructions = Toast.makeText(MainActivity.this,
      //            "Click for search.", Toast.LENGTH_LONG);
      //    instructions.setGravity(Gravity.CENTER, 0, -250);
      //    instructions.show();

      Toast instructions2 = Toast.makeText(MainActivity.this,
              "Click enter with no text in search box \n " +
                      "         to go to the main site.", Toast.LENGTH_LONG);
      instructions2.setGravity(Gravity.CENTER, 0, -200);
      instructions2.show();

      //   Toast instructions3 = Toast.makeText(MainActivity.this,
      //           "Touch above search box to close keyboard.", Toast.LENGTH_LONG);
      //   instructions3.setGravity(Gravity.CENTER, 0, -150);
      //   instructions3.show();*/

      prefs.edit().putBoolean("HAS_VISISTED_BEFORE", true).commit();

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

      DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadFileUrl));
      request.setTitle("Suggestions download.");
      request.setDescription("Suggestions database being downloaded...");

      request.setDestinationInExternalFilesDir(
          getApplicationContext(), "/dbase", "sportsreflinks.db");
      request.setNotificationVisibility(
          DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
      request.allowScanningByMediaScanner();
      // request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
      // "sportsreflinks.db");

      /*  if (!hasVisited) {

           request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
           request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);

      } else {

          request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);

      }*/

      String filePath = prefs.getString("filepath", "");

      Log.i(TAG, "file path is " + filePath);

      fileExist = doesFileExist(filePath);
      Log.i(TAG, "file exists is " + fileExist.toString());

      if (fileExist == true) {

        deleteFileIfExists(filePath);
      }

      myDownloadReference = downloadManager.enqueue(request);

      intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

      receiverDownloadComplete =
          new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
              long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

              if (myDownloadReference == reference) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(reference);
                Cursor cursor = downloadManager.query(query);

                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                int status = cursor.getInt(columnIndex);
                int fileNameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
                String saveFilePath = cursor.getString(fileNameIndex);

                fileExist = doesFileExist(saveFilePath);

                Log.i(TAG, "file exists download complete " + saveFilePath);

                prefs.edit().putString("filepath", saveFilePath).commit();

                int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
                int reason = cursor.getInt(columnReason);

                mlbbutton.setVisibility(View.VISIBLE);
                nhlbutton.setVisibility(View.VISIBLE);
                nbabutton.setVisibility(View.VISIBLE);
                nflbutton.setVisibility(View.VISIBLE);
                cfbbutton.setVisibility(View.VISIBLE);
                cbbbutton.setVisibility(View.VISIBLE);
                olybutton.setVisibility(View.VISIBLE);

                //     mainScreen.setEnabled(true);

                //     mainScreen.setClickable(true);

              }
            }
          };
    }

    mlbbutton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent intentbaseballsearch = new Intent();
            intentbaseballsearch.setClass(getApplicationContext(), MLBsearch.class);
            startActivity(intentbaseballsearch);
          }
        });

    nflbutton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent intentfootballsearch = new Intent();
            intentfootballsearch.setClass(getApplicationContext(), NFLsearch.class);
            startActivity(intentfootballsearch);
          }
        });

    nhlbutton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent intenthockeysearch = new Intent();
            intenthockeysearch.setClass(getApplicationContext(), NHLsearch.class);
            startActivity(intenthockeysearch);
          }
        });

    nbabutton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent intentbasketballsearch = new Intent();
            intentbasketballsearch.setClass(getApplicationContext(), NBAsearch.class);
            startActivity(intentbasketballsearch);
          }
        });

    cfbbutton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent intentcollegefootballsearch = new Intent();
            intentcollegefootballsearch.setClass(getApplicationContext(), CFBsearch.class);
            startActivity(intentcollegefootballsearch);
          }
        });

    cbbbutton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent intentcollegebasketballsearch = new Intent();
            intentcollegebasketballsearch.setClass(getApplicationContext(), CBBsearch.class);
            startActivity(intentcollegebasketballsearch);
          }
        });

    olybutton.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            Intent intentolympicssearch = new Intent();
            intentolympicssearch.setClass(getApplicationContext(), OLYsearch.class);
            startActivity(intentolympicssearch);
          }
        });
  }
  private void startLinksDownload(Context context, Magazine magazine) {
    Log.d(TAG, "Start DownloadLinksTask");

    SQLiteDatabase db = DataBaseHelper.getInstance(context).getWritableDatabase();
    db.beginTransaction();

    ArrayList<String> links = new ArrayList<String>();
    ArrayList<String> assetsNames = new ArrayList<String>();
    //
    String filePath = magazine.isSample() ? magazine.getSamplePdfPath() : magazine.getItemPath();
    PDFParser linkGetter = new PDFParser(filePath);
    SparseArray<LinkInfoExternal[]> linkBuf = linkGetter.getLinkInfo();
    if (linkBuf == null) {
      Log.d(TAG, "There is no links");
      return;
    }
    for (int i = 0; i < linkBuf.size(); i++) {
      int key = linkBuf.keyAt(i);
      Log.d(TAG, "--- i = " + i);
      if (linkBuf.get(key) != null) {
        for (int j = 0; j < linkBuf.get(key).length; j++) {
          LinkInfoExternal extLink = linkBuf.get(key)[j];
          String link = linkBuf.get(key)[j].url;
          Log.d(TAG, "link[" + j + "] = " + link);
          String local = "http://localhost";
          if (link.startsWith(local)) {
            int startIdx = local.length() + 1;
            int finIdx = link.length();
            if (link.contains("?")) {
              finIdx = link.indexOf("?");
            }
            String assetsFile = link.substring(startIdx, finIdx);
            links.add(Magazine.getAssetsBaseURL(magazine.getFileName()) + assetsFile);
            assetsNames.add(assetsFile);
            Log.d(
                TAG, "   link: " + Magazine.getAssetsBaseURL(magazine.getFileName()) + assetsFile);
            Log.d(TAG, "   file: " + assetsFile);

            String uriString = Magazine.getAssetsBaseURL(magazine.getFileName()) + assetsFile;
            Log.d(TAG, "  link to download: " + uriString);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uriString));
            request
                .setVisibleInDownloadsUi(false)
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
                .setDescription("Subtitle for " + magazine.getSubtitle())
                .setTitle("Assets for " + magazine.getTitle())
                .setDestinationInExternalFilesDir(context, null, assetsFile);
            // TODO should use cache directory?
            long downloadManagerID = mDManager.enqueue(request);
            ContentValues cv = new ContentValues();
            cv.put(Magazine.FIELD_FILE_NAME, magazine.getFileName());
            cv.put(Magazine.FIELD_ASSET_FILE_NAME, magazine.getAssetsDir() + assetsFile);
            cv.put(Magazine.FIELD_ASSET_IS_DOWNLOADED, false);
            cv.put(Magazine.FIELD_DOWNLOAD_MANAGER_ID, downloadManagerID);
            db.insert(Magazine.TABLE_ASSETS, null, cv);
          }
        }
      }
    }
    try {
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
  }
Esempio n. 25
0
  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);
  }
Esempio n. 26
0
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   if (item.getItemId() == android.R.id.home) {
     finish();
     overridePendingTransition(R.anim.fade_in, R.anim.slide_out_right);
     return true;
   } else if (item.getItemId() == R.id.action_browser) {
     Intent intent =
         new Intent(
             Intent.ACTION_VIEW,
             Uri.parse(
                 getIntent()
                     .getDataString()
                     .replace(getResources().getString(R.string.IMAGE_SCHEME), "http")));
     startActivity(intent);
     finish();
     return true;
   } else if (item.getItemId() == R.id.action_save) {
     DownloadManager d = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
     if (d != null) {
       DownloadManager.Request r =
           new DownloadManager.Request(
               Uri.parse(
                   getIntent()
                       .getDataString()
                       .replace(getResources().getString(R.string.IMAGE_SCHEME), "http")));
       if (Build.VERSION.SDK_INT >= 11) {
         r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
         r.allowScanningByMediaScanner();
       }
       d.enqueue(r);
     }
     return true;
   } else if (item.getItemId() == R.id.action_copy) {
     if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
       android.text.ClipboardManager clipboard =
           (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
       clipboard.setText(
           getIntent()
               .getDataString()
               .replace(getResources().getString(R.string.IMAGE_SCHEME), "http"));
     } else {
       @SuppressLint("ServiceCast")
       android.content.ClipboardManager clipboard =
           (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
       android.content.ClipData clip =
           android.content.ClipData.newRawUri(
               "IRCCloud Image URL",
               Uri.parse(
                   getIntent()
                       .getDataString()
                       .replace(getResources().getString(R.string.IMAGE_SCHEME), "http")));
       clipboard.setPrimaryClip(clip);
     }
     Toast.makeText(ImageViewerActivity.this, "Link copied to clipboard", Toast.LENGTH_SHORT)
         .show();
   }
   return super.onOptionsItemSelected(item);
 }
 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");
 }
Esempio n. 28
0
 @SuppressLint("NewApi")
 private static void restrictDownloadToWifi(DownloadManager.Request request) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
     request.setAllowedOverMetered(false);
   } else {
     request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
   }
 }
Esempio n. 29
0
 public void downloadFile(String streamUrl, String destPath) {
   Uri url = Uri.parse(streamUrl);
   Uri destP = Uri.fromFile(new File(destPath));
   DownloadManager.Request request = new DownloadManager.Request(url);
   request.setDestinationUri(destP);
   request.setVisibleInDownloadsUi(true);
   request.setAllowedNetworkTypes(
       DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
   downloadManager.enqueue(request);
 }
Esempio n. 30
0
  @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();
  }