在Android中实现方法回调

时间:2012-09-13 23:09:18

标签: android callback

目前在我的项目中,我正在发出Http请求,我希望将不同的http响应发送到不同的回调方法。

我在下面写了一个快速示例来展示我想要做的事情。我知道它可能不会像我想要的那样,但有没有任何干净的解决方案来实现同样的目标?

样品:

活动类:

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
    }
}

服务类:

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);
        } 
    }
}

5 个答案:

答案 0 :(得分:20)

interface OnLoginCompleteListener {
    void onLoginComplete(String response);
}

然后

public void login(String user, String password, OnLoginComplete listener) {
    mOnCompleteListener = listener;
}

protected Object doInBackground(Object... params) {
    mOnCompleteListener.onLoginComplete(response);
}

最后

service.login("user", "password", new OnLoginCompleteListener() {
    public void onLoginComplete(String response) {
        // Handle your response
    }
});

答案 1 :(得分:3)

我想我和你的问题一样。

我一直在寻找一个好的答案,这是对我有用的实现:

首先创建一个包含方法的接口;在我的情况下,我使用典型的onSuccessonFailure,但您可以制作自己的方法:

//MyInterface.java

public interface MyInterface
{
    void onSuccess(String response);
    void onFailure(String response);
}

然后创建课程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");
    }
}

最后在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();
            }
        });
    }
}

答案 2 :(得分:2)

如果我理解正确,建议您通过使用AsyncTask完成您要实现的目标。这里以一种非常简单的方式解释 http://developer.android.com/reference/android/os/AsyncTask.html

此外,我分享了一个如何执行(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());

}

答案 3 :(得分:0)

有几种方法可以解决这个问题。您可以传入Runnable作为回调,或者您可以在Services类中提供覆盖方法,并在主要活动中使用从Services派生的匿名类。如果需要传入参数,还可以定义一个等价于Runnable的接口,您可以在其中定义带有响应参数的方法。

答案 4 :(得分:0)

如何在java中实现回调:

public interface SomeCallbackInterface {
    public void finished(Request req);
}

然后在你的班上你做:

YourReqeust.instantiateWithCallback(new SomeCallbackInterface() {
   @Override
   public void finished(Request req){
      // do something here
   }
});

这与你对任何View.OnClickListener

的处理方式大致相同