如何替换此 Android 代码中的 AsyncTask?

How to replace AsyncTask in this Android code?

我的 android 项目遇到了这个问题:

这个AsyncTaskclass应该是静态的,否则可能会发生泄漏。

如何替换已弃用的 classe AsyncTask 并避免该代码中的泄漏?提前致谢

private class FetchUrl extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try {
            // Fetching the data from web service
            data = downloadUrl(url[0]);
            Log.d("Background Task data", data);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);

    }
}

创建一个名为 CoroutineAsyncTask.kt 的 kotlin class:

abstract class CoroutineAsyncTask<Params,Progress,Result>(){


    open fun onPreExecute(){ }

    abstract fun doInBackground(vararg params: Params?): Result
    open fun onProgressUpdate(vararg values: Progress?){

    }

    open fun onPostExecute(result: Result?){}

    open fun onCancelled(result: Result?){

    }

   protected var isCancelled= false


    //Code
    protected fun publishProgress(vararg progress: Progress?){
        GlobalScope.launch(Dispatchers.Main) {
            onProgressUpdate(*progress)
        }
    }

    fun execute(vararg params: Params?){
        GlobalScope.launch(Dispatchers.Default) {
            val result = doInBackground(*params)
            withContext(Dispatchers.Main){
                onPostExecute(result)
            }
        }
    }

    fun cancel(mayInterruptIfRunnable: Boolean){

    }
}

并在

的代码中实施 CoroutineAsyncTask
private class FetchUrl extends AsyncTask<String, Void, String> {
}

private class FetchUrl extends CoroutineAsyncTask<String, Void, String> {
}

现在你应该没事了。编码愉快,希望对您有所帮助!