加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 检查Download Manager是否下载了该文件

发布时间:2020-12-15 04:26:27 所属栏目:Java 来源:网络整理
导读:如何检查文件是否已下载并运行其安装?我有一个代码: public void downloadUpdate(String url){ DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDescription("Downloading..."); request.setTitle("App Updat
如何检查文件是否已下载并运行其安装?我有一个代码:

public void downloadUpdate(String url){

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription("Downloading...");
    request.setTitle("App Update");
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    String name = URLUtil.guessFileName(url,null,MimeTypeMap.getFileExtensionFromUrl(url));

    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,name);

    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}

解决方法

要检查下载管理器是否已下载该文件,您必须实现BroatcastReceiver.

@Override
public void onReceive(Context context,Intent intent) {
    String action = intent.getAction();
    if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0));
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor cursor = manager.query(query);
        if (cursor.moveToFirst()) {
            if (cursor.getCount() > 0) {
                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    String file = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                    // So something here on success
                } else {
                    int message = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
                    // So something here on failed.
                }
            }
        }
    }
}

但是,我不确定您是否可以通过编程方式安装APK.出于安全考虑,我认为你不能.对于应用程序更新,我认为您应该使用谷歌版本控制.当您使用不同的版本号重新部署应用时,用户应该能够自动更新(除非用户在Google Play上关闭).希望这会有所帮助.

更新

你不需要调用我提到的方法.您只需要在清单xml文件中声明广播接收器,DownloadManager将在下载完成时调用. xml看起来如下所示:

<receiver
        android:name=".BroadcastReceiver"
        android:enabled="true"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
            <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
        </intent-filter>
    </receiver>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读