3

我有一个Service创建AsyncTasks 来下载文件。在活动中,我们创建Runnables 或Thread传递给s 的 s Activity.runOnUiThread()。我无法从服务访问该方法,那么我该如何AsyncTask正确使用(在不阻塞 UI 线程的情况下进行繁重的工作)?

4

1 回答 1

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()该服务即可。

关于如何更新 UI的真正问题。请注意,此方法接收一个ProgressListener实例。它可能看起来像这样:

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

现在您只需从活动中更新 UI(而不是从服务中,它仍然不知道 UI 的样子)。

于 2010-10-05T17:52:31.937 回答