8

目前在我的项目中,我正在发出 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);
        } 
    }
}
4

5 回答 5

21
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
    }
});
于 2012-09-13T23:14:28.217 回答
3

我想我遇到了和你一样的问题。

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

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

//MyInterface.java

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

然后创建类Services

//Services.java

公共类服务
{
    公共无效登录(字符串用户,字符串密码,MyInterface myInterface)
    {
        请求请求 = createLoginRequest(user, password);

        if(/*请求成功*/)
            myInterface.onSuccess("登录成功");

        别的
            myInterface.onFailure("登录失败");
    }
}

最后调用你的方法Activity

//main.java

公共类 Main 扩展 Activity
{  
    @覆盖
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        服务服务 = 新服务();
        service.login("用户", "密码", new Myinterface()
        {
            @覆盖
            公共无效 onSuccess(字符串响应)
            {
                Toast.makeText(getApplicationContext(), 响应, Toast.LENGTH_SHORT).show();
            }

            @覆盖
            公共无效onFailure(字符串响应)
            {
                Toast.makeText(getApplicationContext(), 响应, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
于 2017-03-31T00:54:19.060 回答
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());

}
于 2013-10-09T00:33:26.730 回答
0

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.

于 2012-09-13T23:14:58.810 回答
0

How to implement callbacks in 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

于 2012-09-13T23:16:16.933 回答