获取引用调用从AsyncTask的活动(而不是作为一个内部类) [英] Getting Reference to Calling Activity from AsyncTask (NOT as an inner class)

查看:239
本文介绍了获取引用调用从AsyncTask的活动(而不是作为一个内部类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有可能的,从AsyncTask的是不是一个内部类调用的Activity类的范围内,得到一个参考到活动的发起执行AsyncTask的实例?

Is it at all possible, from within an AsyncTask that is NOT an inner class of the calling Activity class, to get a reference to the instance of Activity that initiated execution of the AsyncTask?

我知道这个线程的,但它并没有完全解决如何引用调用活动。有人建议通过一个参考活动作为参数传递给AsyncTask的构造,然而,据报道,这样做总是会导致一个NullPointerException异常。

I am aware of this thread, however it doesn't exactly address how to reference the calling Activity. Some suggest passing a reference to the Activity as a parameter to the AsyncTask constructor, however, it's reported that doing so will always result in a NullPointerException.

所以,我很茫然。我的AsyncTask提供了强大的功能,我不希望有复制它在的每次的活动想要使用它的一个内部类。必须有一个完美的解决方案。

So, I'm at a loss. My AsyncTask provides robust functionality, and I don't want to have to duplicate it as an inner class in every Activity that wants to use it. There must be an elegant solution.

推荐答案

而优雅的解决方案是真正的尝试的把它当作一个参数(来构造或执行()),看看它的工作原理,而不是假设谁问previous问题的人(当时回答了自己的问题两次)知道他在做什么。我想不出什么东西内在的AsyncTask ,将导致活动是一个坏的构造函数的参数和所有其他的对象只是罚款。

The "elegant solution" is to actually try passing it as a parameter (to the constructor or execute()) and see if it works, rather than assuming the person who asked that previous question (then answered his own question twice) knows what he is doing. I can think of nothing intrinsic to AsyncTask that would cause Activity to be a bad constructor parameter and every other object be just fine.

现在,我都没有通过的活动(或其他上下文)作为参数传递给了的AsyncTask ,因为我的 AsyncTasks 始终是私有内部类。事实上,事实上,你的需要的公开的AsyncTask 对我来说是一个code气味,这表明这些任务应该由调解服务或其它一些控制点。不过,这只是我。

Now, I haven't passed an Activity (or other Context) as a parameter to an AsyncTask, because my AsyncTasks are always private inner classes. In fact, the fact that you want a public AsyncTask to me is a code smell, suggesting these tasks should be mediated by a Service or some other control point. But, that's just me.

更新

有关处理这个模式的一个更好的答案可以在这里找到:<一href="http://stackoverflow.com/questions/3821423/background-task-progress-dialog-orientation-change-is-there-any-100-working/3821998#3821998">Background任务,进度对话框,方向的变化 - 有没有100%的工作液

A better answer for handling this pattern can be found here: Background task, progress dialog, orientation change - is there any 100% working solution?

这篇关于获取引用调用从AsyncTask的活动(而不是作为一个内部类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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