[英]Type-safe alternative for execute parameters in AsyncTask
There are two ways to pass arguments to an AsyncTask
有两种方法可以将参数传递给AsyncTask
execute()
定义第一个通用参数,并使用此类型的列表/数组,并将其通过execute()
传递 execute
通过构造函数传递所有必要的参数,将其存储在字段中,并在execute
访问它们 I find the first approach more readable, but sometimes it lacks flexibility in terms of type-safety, for instance if you want to pass a String, an Integer and a Boolean it seems unclear how to approach this. 我发现第一种方法更具可读性,但是有时在类型安全性方面缺乏灵活性,例如,如果要传递String,Integer和Boolean,似乎不清楚如何实现此方法。
public Result doInBackground(String... params) {
String param1 = params[0];
int param2 = Integer.valueOf(params[1]);
boolean param3 = Boolean.valueOf(params[2]);
// ...
}
String parsing, putting it in a Bundle
, etc. There is always a solution, but I find this unpleasing from a semantic/method signature point of view. 字符串分析,将其放在Bundle
等中。总有解决方案,但是从语义/方法签名的角度来看,这是令人不快的。 Any alternatives? 有其他选择吗?
Why not create a Class Holder for Example 为什么不创建一个类持有者作为例子
static Class Holder {
int i;
String s;
boolean b;
}
public Result doInBackground(Holder... params) {
Holder holder = params[0];
String holder.s;
// ...
}
then send it to the doBackground() through the execute().. i did it a lot of times when i want to send to web 然后通过execute()将它发送到doBackground()。当我想发送到Web时,我做了很多次
this is just an example of crouse. 这只是松鼠的一个例子。 Hope it helps. 希望能帮助到你。
You could use Loaders instead. 您可以改为使用装载程序 。
It can be cumbersome to start with, but you won't have any type-safe issues then, because it works in a complete different manner. 一开始可能很麻烦,但是您不会遇到任何类型安全的问题,因为它的工作方式完全不同。
The main power of loaders is that they work with a manager that is bound to the lifecycle of the Activity/Fragment. 加载程序的主要功能是与绑定到活动/片段生命周期的管理器一起工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.