如何创建/运行的AsyncTask的服务没有runOnUiThread()
-
27-09-2019 - |
题
我有一个创建了下载文件Service
s一个AsyncTask
。在活动中,我们创建Runnable
s或Thread
s,我们传递给Activity.runOnUiThread()
。我无法访问,从服务的方法,所以我怎么使用AsyncTask
正确,(干重活,而不会阻塞UI线程)?
解决方案
如果您的服务只在您的应用程序调用,你可以把它单身,那就试试这个:
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看起来怎么样)。
不隶属于 StackOverflow