Java Code Examples for android.app.DownloadManager.Request#setNotificationVisibility()

The following examples show how to use android.app.DownloadManager.Request#setNotificationVisibility() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebViewActivity.java    From mattermost-android-classic with Apache License 2.0 6 votes vote down vote up
private DownloadListener getDownloadListener() {
    return new DownloadListener() {
        public void onDownloadStart(
            String url,
            String userAgent,
            String contentDisposition,
            String mimetype,
            long contentLength
        ) {
            Uri uri = Uri.parse(url);
            Request request = new Request(uri);
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("File download from Mattermost");

            String cookie = CookieManager.getInstance().getCookie(url);
            if (cookie != null) {
                request.addRequestHeader("cookie", cookie);
            }

            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
       }
    };
}
 
Example 2
Source File: UpdateHandler.java    From Android-Keyboard with Apache License 2.0 5 votes vote down vote up
/**
 * Download latest metadata from the server through DownloadManager for all relevant clients
 *
 * @param context The context for retrieving resources
 * @param metadataUri The client to update
 */
private static void updateClientsWithMetadataUri(
        final Context context, final String metadataUri) {
    Log.i(TAG, "updateClientsWithMetadataUri() : MetadataUri = " + metadataUri);
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".json";
    final Request metadataRequest = new Request(Uri.parse(metadataUri + disambiguator));
    DebugLogUtils.l("Request =", metadataRequest);

    final Resources res = context.getResources();
    metadataRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    metadataRequest.setTitle(res.getString(R.string.download_description));
    // Do not show the notification when downloading the metadata.
    metadataRequest.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    metadataRequest.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.metadata_downloads_visible_in_download_UI));

    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (maybeCancelUpdateAndReturnIfStillRunning(context, metadataUri, manager,
            DictionaryService.NO_CANCEL_DOWNLOAD_PERIOD_MILLIS)) {
        // We already have a recent download in progress. Don't register a new download.
        return;
    }
    final long downloadId;
    synchronized (sSharedIdProtector) {
        downloadId = manager.enqueue(metadataRequest);
        DebugLogUtils.l("Metadata download requested with id", downloadId);
        // If there is still a download in progress, it's been there for a while and
        // there is probably something wrong with download manager. It's best to just
        // overwrite the id and request it again. If the old one happens to finish
        // anyway, we don't know about its ID any more, so the downloadFinished
        // method will ignore it.
        writeMetadataDownloadId(context, metadataUri, downloadId);
    }
    Log.i(TAG, "updateClientsWithMetadataUri() : DownloadId = " + downloadId);
}
 
Example 3
Source File: UpdateHandler.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 5 votes vote down vote up
/**
 * Download latest metadata from the server through DownloadManager for all relevant clients
 *
 * @param context The context for retrieving resources
 * @param metadataUri The client to update
 */
private static void updateClientsWithMetadataUri(
        final Context context, final String metadataUri) {
    Log.i(TAG, "updateClientsWithMetadataUri() : MetadataUri = " + metadataUri);
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".json";
    final Request metadataRequest = new Request(Uri.parse(metadataUri + disambiguator));
    DebugLogUtils.l("Request =", metadataRequest);

    final Resources res = context.getResources();
    metadataRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    metadataRequest.setTitle(res.getString(R.string.download_description));
    // Do not show the notification when downloading the metadata.
    metadataRequest.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    metadataRequest.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.metadata_downloads_visible_in_download_UI));

    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (maybeCancelUpdateAndReturnIfStillRunning(context, metadataUri, manager,
            DictionaryService.NO_CANCEL_DOWNLOAD_PERIOD_MILLIS)) {
        // We already have a recent download in progress. Don't register a new download.
        return;
    }
    final long downloadId;
    synchronized (sSharedIdProtector) {
        downloadId = manager.enqueue(metadataRequest);
        DebugLogUtils.l("Metadata download requested with id", downloadId);
        // If there is still a download in progress, it's been there for a while and
        // there is probably something wrong with download manager. It's best to just
        // overwrite the id and request it again. If the old one happens to finish
        // anyway, we don't know about its ID any more, so the downloadFinished
        // method will ignore it.
        writeMetadataDownloadId(context, metadataUri, downloadId);
    }
    Log.i(TAG, "updateClientsWithMetadataUri() : DownloadId = " + downloadId);
}
 
Example 4
Source File: UpdateHandler.java    From Indic-Keyboard with Apache License 2.0 5 votes vote down vote up
/**
 * Download latest metadata from the server through DownloadManager for all relevant clients
 *
 * @param context The context for retrieving resources
 * @param metadataUri The client to update
 */
private static void updateClientsWithMetadataUri(
        final Context context, final String metadataUri) {
    Log.i(TAG, "updateClientsWithMetadataUri() : MetadataUri = " + metadataUri);
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".json";
    final Request metadataRequest = new Request(Uri.parse(metadataUri + disambiguator));
    DebugLogUtils.l("Request =", metadataRequest);

    final Resources res = context.getResources();
    metadataRequest.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    metadataRequest.setTitle(res.getString(R.string.download_description));
    // Do not show the notification when downloading the metadata.
    metadataRequest.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    metadataRequest.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.metadata_downloads_visible_in_download_UI));

    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (maybeCancelUpdateAndReturnIfStillRunning(context, metadataUri, manager,
            DictionaryService.NO_CANCEL_DOWNLOAD_PERIOD_MILLIS)) {
        // We already have a recent download in progress. Don't register a new download.
        return;
    }
    final long downloadId;
    synchronized (sSharedIdProtector) {
        downloadId = manager.enqueue(metadataRequest);
        DebugLogUtils.l("Metadata download requested with id", downloadId);
        // If there is still a download in progress, it's been there for a while and
        // there is probably something wrong with download manager. It's best to just
        // overwrite the id and request it again. If the old one happens to finish
        // anyway, we don't know about its ID any more, so the downloadFinished
        // method will ignore it.
        writeMetadataDownloadId(context, metadataUri, downloadId);
    }
    Log.i(TAG, "updateClientsWithMetadataUri() : DownloadId = " + downloadId);
}
 
Example 5
Source File: PickerMain.java    From onedrive-picker-android with MIT License 5 votes vote down vote up
@Override
public void onClick(final View v) {
    if (mDownloadUrl == null) {
        return;
    }

    final DownloadManager downloadManager = (DownloadManager)v.getContext().getSystemService(DOWNLOAD_SERVICE);
    final Request request = new Request(mDownloadUrl);
    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    downloadManager.enqueue(request);
}
 
Example 6
Source File: ActionBatch.java    From Android-Keyboard with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(final Context context) {
    if (null == mWordList) { // This should never happen
        Log.e(TAG, "UpdateAction with a null parameter!");
        return;
    }
    DebugLogUtils.l("Downloading word list");
    final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
    final ContentValues values = MetadataDbHelper.getContentValuesByWordListId(db,
            mWordList.mId, mWordList.mVersion);
    final int status = values.getAsInteger(MetadataDbHelper.STATUS_COLUMN);
    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (MetadataDbHelper.STATUS_DOWNLOADING == status) {
        // The word list is still downloading. Cancel the download and revert the
        // word list status to "available".
        manager.remove(values.getAsLong(MetadataDbHelper.PENDINGID_COLUMN));
        MetadataDbHelper.markEntryAsAvailable(db, mWordList.mId, mWordList.mVersion);
    } else if (MetadataDbHelper.STATUS_AVAILABLE != status
            && MetadataDbHelper.STATUS_RETRYING != status) {
        // Should never happen
        Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' : " + status
                + " for an upgrade action. Fall back to download.");
    }
    // Download it.
    DebugLogUtils.l("Upgrade word list, downloading", mWordList.mRemoteFilename);

    // This is an upgraded word list: we should download it.
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".dict";
    final Uri uri = Uri.parse(mWordList.mRemoteFilename + disambiguator);
    final Request request = new Request(uri);

    final Resources res = context.getResources();
    request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    request.setTitle(mWordList.mDescription);
    request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    request.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.dict_downloads_visible_in_download_UI));

    final long downloadId = UpdateHandler.registerDownloadRequest(manager, request, db,
            mWordList.mId, mWordList.mVersion);
    Log.i(TAG, String.format("Starting the dictionary download with version:"
                    + " %d and Url: %s", mWordList.mVersion, uri));
    DebugLogUtils.l("Starting download of", uri, "with id", downloadId);
    PrivateLog.log("Starting download of " + uri + ", id : " + downloadId);
}
 
Example 7
Source File: DownloadsUtil.java    From EdXposedManager with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
private static DownloadInfo add(Builder b) {
    Context context = b.mContext;
    removeAllForUrl(context, b.mUrl);

    if (!b.mDialog) {
        synchronized (mCallbacks) {
            mCallbacks.put(b.mUrl, b.mCallback);
        }
    }

    String savePath = "Download/EdXposedManager";
    if (b.mModule) {
        savePath += "/modules";
    }

    Request request = new Request(Uri.parse(b.mUrl));
    request.setTitle(b.mTitle);
    request.setMimeType(b.mMimeType.toString());
    if (b.mSave) {
        try {
            request.setDestinationInExternalPublicDir(savePath, b.mTitle + b.mMimeType.getExtension());
        } catch (IllegalStateException e) {
            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    } else if (b.mDestination != null) {
        b.mDestination.getParentFile().mkdirs();
        removeAllForLocalFile(context, b.mDestination);
        request.setDestinationUri(Uri.fromFile(b.mDestination));
    }

    request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);

    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    long id = dm.enqueue(request);

    if (b.mDialog) {
        showDownloadDialog(b, id);
    }

    return getById(context, id);
}
 
Example 8
Source File: ActionBatch.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(final Context context) {
    if (null == mWordList) { // This should never happen
        Log.e(TAG, "UpdateAction with a null parameter!");
        return;
    }
    DebugLogUtils.l("Downloading word list");
    final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
    final ContentValues values = MetadataDbHelper.getContentValuesByWordListId(db,
            mWordList.mId, mWordList.mVersion);
    final int status = values.getAsInteger(MetadataDbHelper.STATUS_COLUMN);
    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (MetadataDbHelper.STATUS_DOWNLOADING == status) {
        // The word list is still downloading. Cancel the download and revert the
        // word list status to "available".
        manager.remove(values.getAsLong(MetadataDbHelper.PENDINGID_COLUMN));
        MetadataDbHelper.markEntryAsAvailable(db, mWordList.mId, mWordList.mVersion);
    } else if (MetadataDbHelper.STATUS_AVAILABLE != status
            && MetadataDbHelper.STATUS_RETRYING != status) {
        // Should never happen
        Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' : " + status
                + " for an upgrade action. Fall back to download.");
    }
    // Download it.
    DebugLogUtils.l("Upgrade word list, downloading", mWordList.mRemoteFilename);

    // This is an upgraded word list: we should download it.
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".dict";
    final Uri uri = Uri.parse(mWordList.mRemoteFilename + disambiguator);
    final Request request = new Request(uri);

    final Resources res = context.getResources();
    request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    request.setTitle(mWordList.mDescription);
    request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    request.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.dict_downloads_visible_in_download_UI));

    final long downloadId = UpdateHandler.registerDownloadRequest(manager, request, db,
            mWordList.mId, mWordList.mVersion);
    Log.i(TAG, String.format("Starting the dictionary download with version:"
                    + " %d and Url: %s", mWordList.mVersion, uri));
    DebugLogUtils.l("Starting download of", uri, "with id", downloadId);
    PrivateLog.log("Starting download of " + uri + ", id : " + downloadId);
}
 
Example 9
Source File: DownloadMapActivity.java    From PocketMaps with MIT License 4 votes vote down vote up
/**
 * download map
 *
 * @param view     View
 * @param position item position
 */
private void onClickMapNow(int position)
{
  MyMap myMap = myDownloadAdapter.getItem(position);
  if (myMap.getStatus() == MyMap.DlStatus.Downloading || myMap.getStatus() == MyMap.DlStatus.Unzipping)
  {
    logUser("Already downloading!");
    return;
  }
  else if (myMap.isUpdateAvailable())
  {
    MyMap myMapNew = null;
    if (!myMap.getMapNameNew().isEmpty())
    {          
      int removePos = -1;
      for (int i= 0; i<myDownloadAdapter.getItemCount(); i++)
      {
        if (myDownloadAdapter.getItem(i).getMapName().equals(myMap.getMapName()))
        {
          removePos = i;
        }
        if (myDownloadAdapter.getItem(i).getMapName().equals(myMap.getMapNameNew()))
        {
          position = i;
          myMapNew = myDownloadAdapter.getItem(i);
        }
      }
      if (removePos < 0 || myMapNew == null)
      {
        logUser("OldMap or NewMap missing on json-list!");
        return;
      }
      mapsRV.scrollToPosition(position);
      myDownloadAdapter.remove(removePos);
      if (position > removePos) { position--; }
    }
    MainActivity.clearLocalMap(myMap);
    if (myMapNew != null)
    {
      myMap = myMapNew;
      if (myMap.getStatus() != DlStatus.On_server)
      {
        logUser("New map is: " + myMap.getMapName());
        return;
      }
    }
  }
  else if (myMap.getStatus() == MyMap.DlStatus.Complete)
  {
    logUser("Already downloaded!");
    return;
  }
  myMap.setStatus(MyMap.DlStatus.Downloading);
  myDownloadAdapter.refreshMapView(myMap);
  String vers = "?v=unknown";
  DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
  try
  {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    vers = "?v=" + packageInfo.versionName;
  }
  catch (Exception e) {} // No problem, not important.
  Request request = new Request(Uri.parse(myMap.getUrl() + vers));
  File destFile = MyMap.getMapFile(myMap, MyMap.MapFileType.DlMapFile);
  request.setDestinationUri(Uri.fromFile(destFile));
  request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  request.setMimeType("application/pocketmaps");
  long enqueueId = dm.enqueue(request);
  File idFile = MyMap.getMapFile(myMap, MyMap.MapFileType.DlIdFile);
  IO.writeToFile("" + enqueueId, idFile, false);
  BroadcastReceiver br = createBroadcastReceiver(this, createStatusUpdater(), myMap, enqueueId);
  registerReceiver(br, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  receiverList.add(br);
}
 
Example 10
Source File: ActionBatch.java    From Indic-Keyboard with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(final Context context) {
    if (null == mWordList) { // This should never happen
        Log.e(TAG, "UpdateAction with a null parameter!");
        return;
    }
    DebugLogUtils.l("Downloading word list");
    final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
    final ContentValues values = MetadataDbHelper.getContentValuesByWordListId(db,
            mWordList.mId, mWordList.mVersion);
    final int status = values.getAsInteger(MetadataDbHelper.STATUS_COLUMN);
    final DownloadManagerWrapper manager = new DownloadManagerWrapper(context);
    if (MetadataDbHelper.STATUS_DOWNLOADING == status) {
        // The word list is still downloading. Cancel the download and revert the
        // word list status to "available".
        manager.remove(values.getAsLong(MetadataDbHelper.PENDINGID_COLUMN));
        MetadataDbHelper.markEntryAsAvailable(db, mWordList.mId, mWordList.mVersion);
    } else if (MetadataDbHelper.STATUS_AVAILABLE != status
            && MetadataDbHelper.STATUS_RETRYING != status) {
        // Should never happen
        Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' : " + status
                + " for an upgrade action. Fall back to download.");
    }
    // Download it.
    DebugLogUtils.l("Upgrade word list, downloading", mWordList.mRemoteFilename);

    // This is an upgraded word list: we should download it.
    // Adding a disambiguator to circumvent a bug in older versions of DownloadManager.
    // DownloadManager also stupidly cuts the extension to replace with its own that it
    // gets from the content-type. We need to circumvent this.
    final String disambiguator = "#" + System.currentTimeMillis()
            + ApplicationUtils.getVersionName(context) + ".dict";
    final Uri uri = Uri.parse(mWordList.mRemoteFilename + disambiguator);
    final Request request = new Request(uri);

    final Resources res = context.getResources();
    request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    request.setTitle(mWordList.mDescription);
    request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
    request.setVisibleInDownloadsUi(
            res.getBoolean(R.bool.dict_downloads_visible_in_download_UI));

    final long downloadId = UpdateHandler.registerDownloadRequest(manager, request, db,
            mWordList.mId, mWordList.mVersion);
    Log.i(TAG, String.format("Starting the dictionary download with version:"
                    + " %d and Url: %s", mWordList.mVersion, uri));
    DebugLogUtils.l("Starting download of", uri, "with id", downloadId);
    PrivateLog.log("Starting download of " + uri + ", id : " + downloadId);
}
 
Example 11
Source File: DownloadNewVersionJob.java    From WayHoo with Apache License 2.0 4 votes vote down vote up
@Override
public Void run(JobContext jc) {
	try {
		if (checkDownloadRunning())
			return null;
		if (checkApkExist()) {
			Intent installApkIntent = new Intent();
			installApkIntent.setAction(Intent.ACTION_VIEW);
			installApkIntent.setDataAndType(
					Uri.parse(Preferences.getDownloadPath(mContext)),
					"application/vnd.android.package-archive");
			installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			mContext.startActivity(installApkIntent);
		} else {
			String apkName = mContext.getPackageName()
					+ System.currentTimeMillis() + Constants.APK_SUFFIX;
			// 系统下载程序
			final DownloadManager downloadManager = (DownloadManager) mContext
					.getSystemService(mContext.DOWNLOAD_SERVICE);

			Long recommendedMaxBytes = DownloadManager
					.getRecommendedMaxBytesOverMobile(mContext);

			// 可以在移动网络下下载
			if (recommendedMaxBytes == null
					|| recommendedMaxBytes.longValue() > MAX_ALLOWED_DOWNLOAD_BYTES_BY_MOBILE) {
				allowMobileDownload = true;
			}

			Uri uri = Uri.parse(mUpgradeInfo.getUrl());

			final Request request = new Request(uri);

			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

			int NETWORK_TYPE = DownloadManager.Request.NETWORK_WIFI;
			if (allowMobileDownload) {
				NETWORK_TYPE |= DownloadManager.Request.NETWORK_MOBILE;
			}
			request.setAllowedNetworkTypes(NETWORK_TYPE);
			request.allowScanningByMediaScanner();
			request.setShowRunningNotification(true);
			request.setVisibleInDownloadsUi(true);
			request.setDestinationInExternalPublicDir(
					Environment.DIRECTORY_DOWNLOADS, apkName);
			PackageManager packageManager = mContext.getPackageManager();
			ApplicationInfo applicationInfo = packageManager
					.getApplicationInfo(mContext.getPackageName(), 0);
			Log.i("liweiping",
					"appName = "
							+ packageManager
									.getApplicationLabel(applicationInfo));
			request.setTitle(packageManager
					.getApplicationLabel(applicationInfo));
			request.setMimeType("application/vnd.android.package-archive");

			// id 保存起来跟之后的广播接收器作对比
			long id = downloadManager.enqueue(request);

			long oldId = Preferences.getDownloadId(mContext);
			if (oldId != -1) {
				downloadManager.remove(oldId);
			}

			Preferences.removeAll(mContext);
			Preferences.setDownloadId(mContext, id);
			Preferences.setUpgradeInfo(mContext, mUpgradeInfo);
			Preferences.setDownloadStatus(mContext,
					Constants.DOWNLOAD_STATUS_RUNNING);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 12
Source File: DownloadNewVersionJob.java    From WayHoo with Apache License 2.0 4 votes vote down vote up
@Override
public Void run(JobContext jc) {
	try {
		if (checkDownloadRunning())
			return null;
		if (checkApkExist()) {
			Intent installApkIntent = new Intent();
			installApkIntent.setAction(Intent.ACTION_VIEW);
			installApkIntent.setDataAndType(
					Uri.parse(Preferences.getDownloadPath(mContext)),
					"application/vnd.android.package-archive");
			installApkIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			mContext.startActivity(installApkIntent);
		} else {
			String apkName = mContext.getPackageName()
					+ System.currentTimeMillis() + Constants.APK_SUFFIX;
			// 系统下载程序
			final DownloadManager downloadManager = (DownloadManager) mContext
					.getSystemService(mContext.DOWNLOAD_SERVICE);

			Long recommendedMaxBytes = DownloadManager
					.getRecommendedMaxBytesOverMobile(mContext);

			// 可以在移动网络下下载
			if (recommendedMaxBytes == null
					|| recommendedMaxBytes.longValue() > MAX_ALLOWED_DOWNLOAD_BYTES_BY_MOBILE) {
				allowMobileDownload = true;
			}

			Uri uri = Uri.parse(mUpgradeInfo.getUrl());

			final Request request = new Request(uri);

			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

			int NETWORK_TYPE = DownloadManager.Request.NETWORK_WIFI;
			if (allowMobileDownload) {
				NETWORK_TYPE |= DownloadManager.Request.NETWORK_MOBILE;
			}
			request.setAllowedNetworkTypes(NETWORK_TYPE);
			request.allowScanningByMediaScanner();
			request.setShowRunningNotification(true);
			request.setVisibleInDownloadsUi(true);
			request.setDestinationInExternalPublicDir(
					Environment.DIRECTORY_DOWNLOADS, apkName);
			PackageManager packageManager = mContext.getPackageManager();
			ApplicationInfo applicationInfo = packageManager
					.getApplicationInfo(mContext.getPackageName(), 0);
			Log.i("liweiping",
					"appName = "
							+ packageManager
									.getApplicationLabel(applicationInfo));
			request.setTitle(packageManager
					.getApplicationLabel(applicationInfo));
			request.setMimeType("application/vnd.android.package-archive");

			// id 保存起来跟之后的广播接收器作对比
			long id = downloadManager.enqueue(request);

			long oldId = Preferences.getDownloadId(mContext);
			if (oldId != -1) {
				downloadManager.remove(oldId);
			}

			Preferences.removeAll(mContext);
			Preferences.setDownloadId(mContext, id);
			Preferences.setUpgradeInfo(mContext, mUpgradeInfo);
			Preferences.setDownloadStatus(mContext,
					Constants.DOWNLOAD_STATUS_RUNNING);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}