在Android中实现方法回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12416075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing method callback in Android
提问by AlexCheuk
Currently in my project, I am making Http requests and I want different http response to be sent to different callback methods.
目前在我的项目中,我正在发出 Http 请求,并且我希望将不同的 http 响应发送到不同的回调方法。
I wrote a quick sample below to show what I want to do. I know it probably wont be possible the way i want it, but are there any clean solutions to achieve the same thing?
我在下面写了一个快速示例来展示我想要做什么。我知道这可能不可能像我想要的那样,但是有没有干净的解决方案来实现同样的目标?
Sample:
样本:
Activity Class:
活动类别:
public class Main extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Services service = new Services();
service.login("user", "password", **onLoginComplete()** );
}
public void onLoginComplete(String HTTPResponse){
// Do something with the response
}
}
Service Class:
服务等级:
public class Services{
public void login(String user, String password, CALLBACK){
Request request = createLoginRequest(user, password);
sendRequest(request, CALLBACK);
}
public class sendRequest extends AsyncTask{
@Override
protected Object doInBackground(Object... params) {
// Do Http Request
// Get Response
CALLBACK(response);
}
}
}
回答by Volodymyr Lykhonis
interface OnLoginCompleteListener {
void onLoginComplete(String response);
}
And then
进而
public void login(String user, String password, OnLoginComplete listener) {
mOnCompleteListener = listener;
}
and
和
protected Object doInBackground(Object... params) {
mOnCompleteListener.onLoginComplete(response);
}
and finally
最后
service.login("user", "password", new OnLoginCompleteListener() {
public void onLoginComplete(String response) {
// Handle your response
}
});
回答by Alexkin_Sky
I think I had the same problem as yours.
我想我和你有同样的问题。
I was looking for a good answer and this was the implementation that worked for me:
我一直在寻找一个好的答案,这是对我有用的实现:
First create an interface which contains your methods; in my case I use the typical onSuccess
and onFailure
but you can make your own methods:
首先创建一个包含您的方法的接口;在我的情况下,我使用典型的onSuccess
,onFailure
但您可以制作自己的方法:
//MyInterface.java
public interface MyInterface
{
void onSuccess(String response);
void onFailure(String response);
}
Then create class Services
:
然后创建类Services
:
//Services.java public class Services { public void login(String user, String password, MyInterface myInterface) { Request request = createLoginRequest(user, password); if(/*Request successful*/) myInterface.onSuccess("Login succesful"); else myInterface.onFailure("Login failed"); } }
And finally call the method on your Activity
:
最后调用你的方法Activity
:
//Main.java public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Services service = new Services(); service.login("user", "password", new Myinterface() { @Override public void onSuccess(String response) { Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show(); } @Override public void onFailure(String response) { Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show(); } }); } }
回答by fsvives
If I understand you correctly, what you are trying to achieve is recommended to be done via the use of an AsyncTask. It's explained in a very simple way here http://developer.android.com/reference/android/os/AsyncTask.html
如果我理解正确,建议您通过使用 AsyncTask 来完成您要实现的目标。这里以非常简单的方式解释了 http://developer.android.com/reference/android/os/AsyncTask.html
Additionally, I share an example of how I execute (doInBackground) GET requests to a site and which result then I read (onPostExecute)... hope it helps!
此外,我还分享了一个示例,说明我如何执行 (doInBackground) 对站点的 GET 请求,然后我读取了结果 (onPostExecute)...希望对您有所帮助!
protected InputStream doInBackground(String... example) {
JsonComm jc = new JsonComm();
String baseUrl = "http://www.somewhere.com/get_request.php?data=";
String jcString = jc.encodeJSON("nowyou","seeme");
String url = "";
try {
url = baseUrl + URLEncoder.encode(jcString, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response;
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
response = httpClient.execute(request);
} catch (Exception ex) {
// handle exception here
}finally {
httpClient.getConnectionManager().shutdown();
}
return response.getEntity().getContent();
}
protected void onPostExecute(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sb.toString());
}
回答by kabuko
There are several ways you can handle this. You could pass in a Runnable
for your callback or you could provide a method to override in your Services
class and use an anonymous class derived from Services
in your main activity. If you need to pass in a parameter, you could also define an interface for something equivalent to the Runnable
where you can define a method with a response parameter.
有几种方法可以处理这个问题。您可以Runnable
为您的回调传入一个,或者您可以提供一个方法来覆盖您的Services
类并使用从Services
您的主要活动中派生的匿名类。如果你需要传入一个参数,你也可以定义一个接口,相当于Runnable
你可以定义一个带有响应参数的方法。
回答by hwrdprkns
How to implement callbacks in java:
如何在java中实现回调:
public interface SomeCallbackInterface {
public void finished(Request req);
}
Then in your class you do:
然后在你的课堂上你做:
YourReqeust.instantiateWithCallback(new SomeCallbackInterface() {
@Override
public void finished(Request req){
// do something here
}
});
This pretty much the same thing your do with any View.OnClickListener
这几乎与你对任何 View.OnClickListener