如何将函数作为参数传递给AsynTask [英] How to pass function as paramater to AsynTask
问题描述
因为我是android开发中的新手,所以我需要为我的http请求提供asynctask类.我在一个活动中有很多http请求函数类型,并且我想使其动态化.所以我只想创建一个可以运行我所有功能的AsyncTask函数.
since im new in android development, and i need to provide an asynctask class for my http request. i have a lot of http request function type in one activity, and i want to make it dynamic. so i wanted to create only one AsyncTask function that can run all my function.
这就是例子
private class WebServiceCall extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setVisibility(View.VISIBLE);
pBar.setIndeterminate(false);
pBar.setClickable(false);
}
@Override
protected Void doInBackground(Void... params) {
// a function that i passed
Function01();
return null;
}
@Override
protected void onPostExecute(Void result) {
try{
some code
}
}
catch(Exception e)
{
e.printStackTrace();
}
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setClickable(true);
pBar.setVisibility(View.GONE);
}
}
我只是这样打电话
Oncreate(
new WebServiceCall().execute(function01());
)
任何帮助和代码示例将不胜感激, 谢谢
any help and code sample would be appreciate, thanks
推荐答案
我不知道您将function
用作另一个函数的参数的意思!
I don't know what you mean by a function
as a parameter to another function!
,但是您可以使用Interfaces
来实现此目的.
but you can use Interfaces
for this purpose.
例如:
创建一个可以在onPostExecute()
public interface ResponseCallback {
void onRespond();
}
,在调用asynckTask之前,请像这样定义它:
and before calling asynckTask define it like this:
ResponseCallback callback = new ResponseCallback() {
@Override
public void onRespond() {
//code to be done after calling it from onPostExecute
}
};
并将callback
传递到asynckTask
的constructor
并在onPostExecute
当然,您可以将interface
的签名修改为所需的内容.
of course you can modify the signature of the interface
to what ever you want.
这篇关于如何将函数作为参数传递给AsynTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!