2016-11-23 58 views
1

在Unity問題上,我們詢問了timescouple,但從未回答。如何在後臺下載文件而不管應用程序狀態如何?

我需要做的就是創建一個Android pluugin,它從給定的URL下載少量文件,並在通知面板中顯示下載進度。即使我的Unity應用程序失焦,下載仍應繼續。

http://www.cuelogic.com/blog/wp-content/uploads/2013/10/downloadmanager_31230_l.png

這裏是一個代碼peice的,我現在所擁有的:

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代碼中獲取紋理結果?

任何國王的幫助表示讚賞。

回答

2

我有同樣的問題。起初,我使用了一個在後臺工作的服務,並下載了我需要的文件,包括計算進度和完成事件。

然後,我讓我的插件更簡單易用。您創建一個Java對象的實例,併爲其提供響應的名稱和方法名稱。我使用json來序列化和反序列化java和C#對象,因爲只有字符串可以在Unity的MonoBehaviour對象和java對象之間傳遞。

這裏是downnload看起來如何在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,這樣你可以得到的進展,並檢查文件是否仍然在下載一旦您的應用程序已重新啓動(使用SharedPreferences \ PlayerPrefs來存儲它們)

+0

看起來不錯,接近我的想法。但我想知道如何去超過1個文件。例如,我有500個圖像文件可供下載。我不想用500個下載進度條(如果允許下載併發文件)氾濫通知面板。是否有可能以某種方式顯示集體進步。在Unity中,我將使用文件計數來計算進度(下載的100/500文件=完成20%)。最後,如何從存儲中訪問Unity中下載的文件?對於nooby問題抱歉,因爲我沒有太多的本地開發或插件的經驗:) –

+0

你添加'request.setNotificationVisibility(false)',然後把你自己的通知,顯示進度。 – gilgil28

2

如果你希望它繼續下去,即使統一不是焦點,那麼你不能在Unity中的C#中使用WWW類來完成它。

如果我想這樣做,我可能會寫一個原生Android插件,開始下載服務

從官方谷歌文檔:

A服務是可以執行長時間運行在後臺 操作的應用組件,並且它不向用戶提供 接口。另一個應用程序組件可以啓動服務,並且即使用戶切換到另一個應用程序,它也會繼續在後臺運行。

服務沒有那麼複雜,你意圖,就像你的活動開始他們有很多的例子在線爲這種類型的服務。

下面是關於服務的官方Android文檔:https://developer.android.com/guide/components/services.html

相關問題