Android中的AsnycTask [英] AsnycTask in android

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

问题描述

我已经使用AsnycTask从Sql Server获取数据.
我在方法下面创建AsnycTask对象:

I have use AsnycTask for get Data from Sql Server.
I Create AsnycTask object below method:

new MyAsnycTask().execute(new String[]{"......"});


我的问题是:
如何在AsnycTask类中实现OnCancel(),以便我们杀死当前的AsnycTask对象,因为我们需要多次创建AsnycTas对象.


My Question is:
How to implement OnCancel() in AsnycTask Class , So that we have kill Current AsnycTask object,Because We have multiple time create Object of AsnycTas.

推荐答案

在每个AsyncTask中,您实现onCancelled方法:

In every AsyncTask, you implement the onCancelled method:

@Override
protected void onCancelled() {
    /*Release your resources, such as closing DB connections, abort downloads in
    progress, etc*/
}



现在,在doInBackground()完成时,在AsyncTask上调用cancel()将导致执行onCancelled()而不是onPostExecute().请注意,onCancel不会立即被调用(如上所述,doInBackground完成时会被调用),但是会设置一个标志,可以通过yourAsyncTask.isCancelled()进行访问.这就是为什么通常在循环中从doInBackground方法定期检查此标志的正确做法(并由Android开发指南建议)的原因:



Now, calling cancel() on an AsyncTask will cause onCancelled() instead of onPostExecute() to be executed when doInBackground() is finished. Notice that onCancel isn''t immediately called (as said, it''s called when doInBackground is finished), but a flag is set, which can be accessed via yourAsyncTask.isCancelled(). This is why it''s proper practice (and recommended by Android development guidelines) to periodically check this flag from your doInBackground method, usually in a loop:

@Override
protected Object doInBackground(Object... x) {
    while (!isCancelled()) {
      // Do your work
      return workProcessingResult;
    }
    return null;
 }



进一步阅读此处[^]



Further reading here[^]


这篇关于Android中的AsnycTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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