在 android 中从 downloadManager 找到下载完成

Finding download complete from downloadManager in android

我正在使用 DownloadManager 从网络服务器从我的 android 应用程序将文件下载到设备外部存储器。我需要在完成此下载后启动另一个功能。我的文件下载代码是这样的:

String url = "http://192.168.1.105/download/file.ext";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "files.ext");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);

请建议如何获得类似 onDownloadComplete.....

您可以将 ACTION_DOWNLOAD_COMPLETE 与 BroadcastReceiver

一起使用
public class DonwloadCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // get complete download id
        long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        // to do here
    }
}

我在以下位置找到了答案:DownloadManager.ACTION_DOWNLOAD_COMPLETE broadcast receiver receiving same download id more than once with different download statuses in Android
我的代码是这样的:

private boolean downloadComplete(long downloadId){
        DownloadManager dMgr = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Cursor c= dMgr.query(new DownloadManager.Query().setFilterById(downloadId));

        if(c.moveToFirst()){
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));

            if(status == DownloadManager.STATUS_SUCCESSFUL){
                return true; //Download completed, celebrate
            }else{
                int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                Log.d(TAG, "Download not correct, status [" + status + "] reason [" + reason + "]");
                return false;
            }
        }
        return false;
    }
registerReceiver(onComplete,
                 new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

参考this