有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在后台下载文件,而不考虑应用程序的状态?

这个问题已经被问了一大堆关于团结的问题,但从未得到回答

我所需要做的就是创建一个Android Plugin,它可以从给定的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...
    }
}

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

任何帮助都是感激的


共 (2) 个答案

  1. # 1 楼答案

    我也有同样的问题。起初,我使用了一个在后台工作的服务,下载了我需要的文件,包括计算进度和完成事件

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

    以下是DownLoad在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,以便获得进度,并在应用程序重新启动后检查文件是否仍在下载(使用SharedReferences\PlayerRefers存储它们)

  2. # 2 楼答案

    如果你想让它持续下去,即使在统一没有被关注的时候,那么你不能在C#中与WWW类保持统一

    如果我想这样做,我可能会编写一个原生Android插件,启动下载服务

    来自谷歌官方文档:

    A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application.

    服务没有那么复杂,你可以像开始一项活动一样从意图开始,网上有很多这类服务的例子

    以下是有关服务的官方Android文档:https://developer.android.com/guide/components/services.html