Update progressbar from AsyncTaskLoader?

前端 未结 6 1725
粉色の甜心
粉色の甜心 2021-01-31 05:30

When using a AsyncTaskLoader how would you update a progressbar showing the status as it is being updated? Normally you wait for the callback to remove when done, but how to do

6条回答
  •  忘了有多久
    2021-01-31 06:15

    I just had this problem. I used a static AtomicInteger in my activity to store the progress. The loader updates it via a callback and the activity polls it and displays the progress.

    In the loader callback onLoadFinished I hide my progress panel, which causes the polling loop to exit.

    Usually I'd avoid static state, but I think overall this is simpler than the alternatives. In my case, I have a different layout in landscape, so I'm happier leaving the orientation changes behaving as normal.

    private Handler progressHandler; // init with new Handler(getMainLooper())
    private static AtomicInteger progress = new AtomicInteger(0);
    
    ...
    
    private void beginProgressUiUpdates() {
        progress.set(0);
        displayProgress();
        progressHandler.postDelayed(pollProgress, PROGRESS_POLL_PERIOD_MILLIS);
    }
    
    private Runnable pollProgress = new Runnable() {
        public void run() {
            if (findViewById(R.id.progressPanel).getVisibility() == View.VISIBLE) {
                displayProgress();
                progressHandler.postDelayed(pollProgress, PROGRESS_POLL_PERIOD_MILLIS);
            }
        }
    };
    
    private void displayProgress() {
        ((ProgressBar)findViewById(R.id.progressBar)).setProgress(progress.get());
    }
    

提交回复
热议问题