如何替换此 Android 代码中的 AsyncTask? [英] How to replace AsyncTask in this Android code?

查看:41
本文介绍了如何替换此 Android 代码中的 AsyncTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm getting this issue on my android project:

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

This AsyncTask class should be static or leaks might occur.

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

How to replace the deprecated classe AsyncTask and avoid leaks in that code ? Thanks in advance

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 类:

Make a kotlin class called CoroutineAsyncTask.kt:

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

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

Now you should be fine. Happy coding, hope that helps!

这篇关于如何替换此 Android 代码中的 AsyncTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆