gpt4 book ai didi

java - 无论应用程序状态如何,如何在后台下载文件?

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:42 27 4
gpt4 key购买 nike

这已被问到 coupletimes关于 Unity 问题,但从未回答。

我需要做的就是创建一个 Android 插件,它从给定的 url 下载一些文件并在通知面板中显示下载进度。即使我的 Unity 应用程序失焦,下载也应该继续。


(来源:cuelogic.com)

这是我现在拥有的一段代码:

void DownloadFiles(string[] urls)
{
foreach(var url in urls)
{
StartCoroutine(DownloadFile_CR(url));
}
}

IEnumerator DownloadFile_CR(string url)
{
WWW www = new WWW(url);
while(!www.isDone)
{
yield return null;
}
if(www.error == null)
{
//file downloaded. do something...
}
}

这些是一些纹理文件。那么如何从原生 Android 代码中获取纹理结果呢?

感谢任何国王的帮助。

最佳答案

我遇到了同样的问题。起初,我使用在后台运行的服务并下载我需要的文件,包括计算进度和完成事件。

然后,我使我的插件更加简单易用。您创建一个 Java 对象的实例,为其提供响应的 GameObject 名称和方法名称。我使用json序列化和反序列化java和C#对象,因为Unity的MonoBehaviour对象和java对象之间只能传递字符串。

这是下载在 android 插件中的样子:

            Uri Download_Uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);

//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(true);
//Set the local destination for the downloaded file to a path within the application's external files directory
String[] split = url.split("/");
request.setDestinationInExternalFilesDir(activity, null, split[split.length-1]);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Downloading " + title);
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloading " + name);

request.setVisibleInDownloadsUi(false);

//Enqueue a new download and get the reference Id
long downloadReference = downloadManager.enqueue(request);

然后您可以将引用 ID 发送回 unity,这样您就可以获得进度并在您的应用程序重新启动后检查文件是否仍在下载(使用 SharedPreferences\PlayerPrefs 来存储它们)

关于java - 无论应用程序状态如何,如何在后台下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40763862/

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