如何在这个Android代码中替换AsyncTask



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

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

如何替换不推荐使用的类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类

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> {
}

现在你应该没事了。快乐的编码,希望有帮助!

最新更新