【问题标题】:How to replace AsyncTask in this Android code?如何在此 Android 代码中替换 AsyncTask?
【发布时间】:2021-09-09 04:15:51
【问题描述】:

我在我的 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);

    }
}

【问题讨论】:

    标签: android android-asynctask deprecated


    【解决方案1】:

    创建一个名为 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> {
    }
    

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

    【讨论】:

    • 非常感谢!
    • 不客气 :) 勾选它作为正确答案以表明它对您有帮助。谢谢:)
    • 投票箭头下方有一个钩子。点击它。谢谢;)
    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 2020-09-09
    • 2016-01-03
    • 2015-02-20
    • 2020-12-21
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多