how do i implement a background thread using javautilconcurrent?

Here’s an example of how you might use an ExecutorService within your Activity/Fragment:

// Create some member variables for the ExecutorService 
// and for the Handler that will update the UI from the main thread
ExecutorService mExecutor = Executors.newSingleThreadExecutor();
Handler mHandler = new Handler(Looper.getMainLooper());

// Create an interface to respond with the result after processing
public interface OnProcessedListener {
    public void onProcessed(Event result);
}

private void processInBg(final String url, final boolean finished){
    
    final OnProcessedListener listener = new OnProcessedListener(){
        @Override
        public void onProcessed(Event result){
            // Use the handler so we're not trying to update the UI from the bg thread
            mHandler.post(new Runnable(){
                @Override
                public void run(){
                    // Update the UI here
                    updateUi(result);
                    
                    // ...
                    
                    // If we're done with the ExecutorService, shut it down.
                    // (If you want to re-use the ExecutorService,
                    // make sure to shut it down whenever everything's completed
                    // and you don't need it any more.)
                    if(finished){
                        mExecutor.shutdown();
                    }
                }
            });
        }
    };
    
    Runnable backgroundRunnable = new Runnable(){
        @Override
        public void run(){
            // Perform your background operation(s) and set the result(s)
            Event result = Utils.fetchEarthquakeData(url);
            
            // ...
            
            // Use the interface to pass along the result
            listener.onProcessed(result);
        }
    };
    
    mExecutor.execute(backgroundRunnable);
}

Then, wherever you need to trigger your background processing:

processInBg("some_url", true);

Depending on your situation, you’ll want to customize your implementation of ExecutorService to better suit your needs.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top