简体   繁体   English

如何使用 java.util.concurrent 包实现后台线程?

[英]How to implement a background thread using java.util.concurrent package?

This is the code I used first but in latest Android version AsyncTask class is deprecated and therefore it was not responding and then I used the Thread class but that class is also not working.这是我首先使用的代码,但在最新的 Android 版本中不推荐使用AsyncTask类,因此它没有响应,然后我使用了Thread类,但该类也不起作用。 I want the same result as I was getting with the AsyncTask class.我想要与使用AsyncTask类获得的结果相同的结果。 I know that I have to use some executor class of java.util.concurrent package but don't know which and how to use it.我知道我必须使用 java.util.concurrent 包的一些执行程序类,但不知道哪个以及如何使用它。 Please help me with this thing.请帮我解决这个问题。

private static final String USGS_REQUEST_URL =
            "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-05-02&minfelt=50&minmagnitude=5";

EarthquakeAsyncTask task = new EarthquakeAsyncTask();
        task.execute(USGS_REQUEST_URL);
private class EarthquakeAsyncTask extends AsyncTask<String, Void, Event> {

        @Override
        protected Event doInBackground(String... urls) {

            // Perform the HTTP request for earthquake data and process the response.
            Event result = Utils.fetchEarthquakeData(urls[0]);
            return result;
        }

        @Override
        protected void onPostExecute(Event result) {
            // Update the information displayed to the user.
            updateUi(result);
        }
    }
private static final String USGS_REQUEST_URL =
            "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-05-02&minfelt=50&minmagnitude=5";

earthquakeRunnable runnable = new earthquakeRunnable(USGS_REQUEST_URL);
        runnable.start();

private class earthquakeRunnable extends Thread{

            String urls;
            earthquakeRunnable(String url){
                this.urls = url;
            }
            @Override
            public void run() {
                // Perform the HTTP request for earthquake data and process the response.
                Event result = Utils.fetchEarthquakeData(urls);
                // Update the information displayed to the user
                updateUi(result);
            }
        }

Here's an example of how you might use an ExecutorService within your Activity/Fragment:以下是如何在 Activity/Fragment 中使用 ExecutorService 的示例:

// 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.根据您的情况,您需要自定义 ExecutorService 的实现以更好地满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM