回答

2

如果你的服務只在您的應用程序調用,你可以把它單身,那就試試這個:

public class FileDownloaderService extends Service implements FileDownloader { 
    private static FileDownloaderService instance; 

    public FileDownloaderService() { 
     if (instance != null) { 
      throw new IllegalStateException("This service is supposed to be a singleton"); 
     } 
    } 

    public static FileDownloaderService getInstance() { 
     // TODO: Make sure instance is not null! 
     return instance; 
    } 

    @Override 
    public void onCreate() { 
     instance = this; 
    } 

    @Override 
    public IBinder onBind(@SuppressWarnings("unused") Intent intent) { 
     return null; 
    } 

    @Override 
    public void downloadFile(URL from, File to, ProgressListener progressListener) { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       // Perform the file download 
      } 
     }).start(); 
    } 
} 

現在你可以直接調用你的服務方法。所以只需撥打downloadFile()即可使服務正常工作。

關於您的real如何更新UI的問題。請注意,此方法收到一個ProgressListener實例。它看起來是這樣的:

public interface ProgressListener { 
    void startDownloading(); 
    void downloadProgress(int progress); 
    void endOfDownload(); 
    void downloadFailed(); 
} 

現在,您只需更新從活動的UI(未從服務,這仍然是不知道的UI的樣子)。

+0

我認爲構造函數'public FileDownloaderService()'應該是'private'。這就是Singletons應該如何工作的原理;-) – damienix 2011-04-07 18:13:39

+0

幾個月前你看到自己的代碼很有趣,而且它已經看起來很醜陋:-O。你是對的,它應該是私人的。但是我相信它不會工作(我的代碼在答案中都沒有),因爲操作系統會使用無參數構造函數來創建服務。對? – espinchi 2011-04-09 19:38:26

+0

這只是一個小建議。我更喜歡Android noob;)但是使用無自變量的構造函數創建服務時出現了什麼問題?據我所知,'AsyncTask'上的'onProgressUpdate'可以更新用戶界面,所以也許這會是一個更好的解決方案。 – damienix 2011-04-11 13:24:14

相關問題