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

The following examples show how to use android.app.DownloadManager.Request#setTitle() . 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: DownloadMaster.java    From uPods-android with Apache License 2.0 6 votes vote down vote up
public void download(DownloadTask task) {
    //TODO better path
    DownloadManager downloadManager = (DownloadManager) UpodsApplication.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
    Uri episodUri = Uri.parse(task.track.getAudeoUrl());
    String trackName = GlobalUtils.getCleanFileName(task.track.getTitle()) + ".mp3";
    String mediaItemName = GlobalUtils.getCleanFileName(task.mediaItem.getName());
    String finalPath = PODCASTS_DOWNLOAD_DIRECTORY + "/" + mediaItemName + "/" + trackName;
    finalPath = Environment.getExternalStorageDirectory() + finalPath;
    Request request = new Request(episodUri);
    request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
    request.setTitle(task.track.getTitle());
    request.setDescription(task.track.getSubTitle());
    request.setDestinationUri(Uri.fromFile(new File(finalPath)));
    task.downloadId = downloadManager.enqueue(request);
    task.filePath = finalPath;
    allTasks.add(task);
    Logger.printInfo(DM_LOG, "Starting download episod " + trackName + " to " + finalPath);
    runProgressUpdater();
}
 
Example 2
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 3
Source File: IssueDetailsFragment.java    From magpi-android with MIT License 6 votes vote down vote up
public void downloadIssue() {
    if(!this.canDisplayPdf(getActivity())) {
        Toast.makeText(getActivity(), getActivity().getString(R.string.pdf_reader_required), Toast.LENGTH_LONG).show();
        return;
    }
    
    String file = issue.getId() + ".pdf";
    File magPiFolder = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Config.ISSUE_FOLDER);
    magPiFolder.mkdirs();
    File pdf = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Config.ISSUE_FOLDER, file);
    if(pdf.exists() && !isDownloading(issue.getPdfUrl())) {
        Intent intentPdf = new Intent(Intent.ACTION_VIEW);
        intentPdf.setDataAndType(Uri.fromFile(pdf), "application/pdf");
        startActivity(intentPdf);
    } else if (!isDownloading(issue.getPdfUrl())) {
    	menu.findItem(R.id.menu_view).setVisible(false);
    	menu.findItem(R.id.menu_cancel_download).setVisible(true);
        Request request = new Request(Uri.parse(issue.getPdfUrl()));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setTitle(getActivity().getString(R.string.app_name) + " n�" + issue.getId());
        request.setDescription(getActivity().getString(R.string.download_text) + " n�" + issue.getId());
        request.setDestinationInExternalPublicDir(Config.ISSUE_FOLDER, file);
        dm.enqueue(request);
    }
}
 
Example 4
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 5
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 6
Source File: IDownloadManagerImpl.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized long addDownload(File destFolder, String url, boolean wifiOnly, String title) {
    long dmid = -1;

    //Need to check first if the download manager service is enabled
    if(!isDownloadManagerEnabled())
        return dmid;

    // skip if URL is not valid
    if(url == null) {
        // URL is null
        return dmid;
    }
    url = url.trim();
    if (url.length() == 0) {
        // URL is empty
        return dmid;
    }

    logger.debug("Starting download: " + url);

    Uri target = Uri.fromFile(new File(destFolder, Sha1Util.SHA1(url)));
    Request request = new Request(Uri.parse(url));
    request.setDestinationUri(target);
    request.setTitle(title);

    if (wifiOnly) {
        request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
    } else {
        request.setAllowedNetworkTypes(Request.NETWORK_WIFI | Request.NETWORK_MOBILE);
    }

    dmid = dm.enqueue(request);

    return dmid;
}
 
Example 7
Source File: PluginDownloader.java    From geoar-app with Apache License 2.0 5 votes vote down vote up
public static void downloadPlugin(PluginDownloadHolder dataSource) {

		Request request = new DownloadManager.Request(
				dataSource.getDownloadLink());
		request.setDestinationInExternalFilesDir(
				GeoARApplication.applicationContext, null,
				dataSource.getIdentifier() + ".apk");
		request.setTitle("GeoAR Data Souce Download");
		request.setMimeType("application/vnd.52north.datasources");
		request.setDescription(dataSource.getName());
		currentDownloads.add(mDownloadManager.enqueue(request));
	}
 
Example 8
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 9
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 10
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 11
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 12
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 13
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 14
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;
}