Utils安卓开发Android知识

调用系统下载功能更新apk

2017-06-05  本文已影响51人  麋鹿原

Activity中调用系统下载功能并在通知栏显示:

public static final String MIME_TYPE = "application/vnd.android.package-archive";
public long startDownload(String uri, String title, String description, String fileName, String mimeType) {
    DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request req = new DownloadManager.Request(Uri.parse(uri));

    req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

    req.allowScanningByMediaScanner();
    req.setVisibleInDownloadsUi(true);
    req.setTitle(title);
    req.setDescription(description);
    req.setMimeType(mimeType);

    return dm.enqueue(req);
}

注册下载完成广播

用到自定义的工具类ApkUpdateUtils中方法:

public static void installApk(Context context, long downloadApkId) {
    DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadFileUri = dm.getUriForDownloadedFile(downloadApkId);
    installApk(context, downloadFileUri);
}

public static void installApk(Context context, Uri downloadFileUri) {
    try {
        if (downloadFileUri != null) {
            String path = downloadFileUri.getPath();
            Log.d(TAG, downloadFileUri.toString() + "; path=" + path);
            install(context, downloadFileUri);
        } else {
            Log.e(TAG, "Download failed");
        }
    } catch (ActivityNotFoundException e) {
        Log.e(TAG, e.toString());
//            installFromFile(context);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}

public static void install(Context context, Uri downloadFileUri) {
    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(install);
}
上一篇 下一篇

猜你喜欢

热点阅读