How to create / run AsyncTask in a service without runOnUiThread ()

I have Serviceone that creates AsyncTaskfiles to upload. In the actions we create Runnableor Threadwhich we pass to Activity.runOnUiThread(). I can’t access this method from the service, so how to use it correctly AsyncTask(do the hard work without blocking the user interface thread)?

+3
source share
1 answer

If your service is called only from your application, and you can make it single, try the following:

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(), .

, . , ProgressListener. :

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

( , , ).

+2

Source: https://habr.com/ru/post/1759249/


All Articles