gpt4 book ai didi

java - 检查下载管理器是否下载了文件

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:36 24 4
gpt4 key购买 nike

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

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 中关闭)。希望这会有所帮助。

更新

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

关于java - 检查下载管理器是否下载了文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29335110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com