2012-09-13 29 views
6

Hiện tại trong dự án của tôi, tôi đang thực hiện các yêu cầu Http và tôi muốn phản hồi http khác nhau được gửi đến các phương thức gọi lại khác nhau.Thực hiện gọi lại phương thức trong Android

Tôi đã viết một mẫu nhanh dưới đây để hiển thị những gì tôi muốn làm. Tôi biết nó có lẽ sẽ không thể theo cách tôi muốn nó, nhưng có bất kỳ giải pháp sạch để đạt được điều tương tự?

mẫu:

Hoạt động 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); 
     } 
    } 
} 

Trả lời

20
interface OnLoginCompleteListener { 
    void onLoginComplete(String response); 
} 

Và sau đó

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

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

và cuối cùng

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

Hãy để tôi thử rằng – AlexCheuk

+0

Hai lớp học sẽ chia sẻ Giao diện OnLoginCompleteListener như thế nào? – AlexCheuk

+0

Giống như bạn chia sẻ tất cả SDK Android và các lớp học của bạn :) Đặt nó ở đâu đó, bên trong lớp Dịch vụ của bạn chẳng hạn. –

0

Có một số cách bạn có thể xử lý này. Bạn có thể chuyển vào số Runnable để gọi lại hoặc bạn có thể cung cấp phương thức ghi đè trong lớp Services và sử dụng lớp ẩn danh bắt nguồn từ Services trong hoạt động chính của bạn. Nếu bạn cần truyền vào một tham số, bạn cũng có thể định nghĩa một giao diện cho một cái gì đó tương đương với Runnable nơi bạn có thể định nghĩa một phương thức có tham số đáp ứng.

0

Làm thế nào để thực hiện callbacks trong java:

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

Sau đó, trong lớp học của bạn, bạn cần làm:

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

này khá nhiều điều tương tự làm của bạn với bất kỳ View.OnClickListener

2

Nếu tôi hiểu chính xác, những gì bạn đang cố gắng đạt được được khuyến nghị thực hiện thông qua việc sử dụng AsyncTask. Nó được giải thích một cách rất đơn giản ở đây http://developer.android.com/reference/android/os/AsyncTask.html

Ngoài ra, tôi chia sẻ một ví dụ về cách tôi thực hiện (doInBackground) GET yêu cầu đến một trang web và kết quả sau đó tôi đọc (onPostExecute) ... hy vọng nó sẽ giúp!

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

} 
2

Tôi nghĩ rằng tôi có cùng vấn đề với bạn.

Tôi đang tìm kiếm câu trả lời hay và đây là triển khai đã làm việc cho tôi:

Trước tiên, tạo giao diện chứa phương pháp của bạn; trong trường hợp của tôi, tôi sử dụng điển hình onSuccessonFailure nhưng bạn có thể làm phương pháp của riêng bạn:

//MyInterface.java 

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

Sau đó tạo lớp 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"); 
    } 
} 

Và cuối cùng gọi phương thức trên của bạn 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(); 
      } 
     }); 
    } 
} 
+0

điều gì sẽ xảy ra nếu lớp dịch vụ của tôi cũng hoạt động, tôi không thể tạo đối tượng Hoạt động ..! – Shailesh

+0

Đúng vậy, tại sao Tôi muốn một dịch vụ trong một hoạt động? Ý tôi là, bạn đang thực hiện một authentcation, và bạn cần một yêu cầu asyncronous với các thông tin đăng nhập vào máy chủ, đó là một dịch vụ với = callback = (back-end), và trong hoạt động bạn có đầu vào và nút của bạn (front-end), bạn biết những gì tôi có nghĩa là? Tôi không chắc chắn nếu có một cách khác, tôi đã không tìm thấy bất kỳ khác, nhưng nó có ý nghĩa đối với tôi. –

Các vấn đề liên quan