[英]How to replace AsyncTask in this Android code?
我在我的 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> {
}
現在你應該沒事了。 快樂編碼,希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.