android 检查下载管理器是否下载了该文件

h5qlskok  于 2023-05-05  发布在  Android
关注(0)|答案(3)|浏览(213)

如何检查文件是否已下载并运行其安装?我有一个代码:

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);
}
oo7oh9g9

oo7oh9g91#

若要检查下载管理器是否下载了该文件,必须实现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关闭).希望这会有所帮助。

更新

您不需要调用我提到的方法。你只需要在你的manifest 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>
deikduxw

deikduxw2#

这是一个相对简单的方法。它为我工作:您需要在manifest文件中添加<receiver>标记,如下所示:

<application>
 <receiver
            android:name= "com.example.checkDownloadComplete" <!-- add desired full name here --> 
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
            </intent-filter>
 </receiver>
 </application>

这将为下载完成的事件注册广播接收器。这将在下载完成后立即调用类中的onReceive()方法。请记住,您需要extend BroadcastReceiver类,而不是implement它。我声明了一个布尔变量作为切换来检查下载完成。因此,你的Java类应该是这样的:

public static class checkDownloadComplete extends BroadcastReceiver{

     public static boolean isDownloadComplete= false;

     @Override
     public void onReceive(Context context, Intent intent) {
         isDownloadComplete = true;
         Log.i("Download completed?", String.valueOf(isDownloadComplete));
     }

}

要等待或检查是否已从任何其他类完成下载,请在所需的适当位置使用以下简单代码:

while(!checkDownloadComplete.isDownloadComplete){

    // add necessary code to be executed before completion of download
}
//code after completion of download

但请记住,如果需要在项目中多次检查它,则需要事先重置isDownloadComplete的值。

wpx232ag

wpx232ag3#

如果您希望系统在下载完成时通知您,您可以使用BroadcastReceiver解决方案。
但是,如果你想手动获取下载的状态,你可以使用此代码,你不需要向清单文件添加接收器。
注意:该接口是出于测试目的而添加的,如果您愿意,可以放弃它。

interface Downloader {
    fun downloadFile(url: String,folderName:String,fileName:String): Long
}

class AndroidDownloader(
    private val context: Context
): Downloader {

    private val downloadManager = context.getSystemService(DownloadManager::class.java)

    override fun downloadFile(url: String,folderName:String,fileName:String): Long {
        val request = DownloadManager.Request(url.toUri())
            .setMimeType("image/jpeg")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
            .setTitle(fileName)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "$folderName/$fileName")
        return downloadManager.enqueue(request)
    }

    fun is_download_complete(downloadId: Long): Boolean {
        val query = DownloadManager.Query()
        query.setFilterById(downloadId)
        val cursor = downloadManager?.query(query)
        if (cursor == null) {
            return false
        }
        if (!cursor.moveToFirst()) {
            cursor.close()
            return false
        }
        val columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
        val status = cursor.getInt(columnIndex)
        cursor.close()
        return status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED
    }
}

相关问题