[android]返回值从 Service 到异步方法Activity

标签: Java Android
发布时间: 2016/9/26 4:10:31
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有 Service 我用来使 web 的类 service 调用使用凌空︰

public class AccountService {
    public static void forgotPassword(Context c, String emailAddress) {

        String url = "myUrl";

        JsonArrayRequest request = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // done
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        Volley.newRequestQueue(c).add(request);

    }

}

我跟它从 Activity 像这样︰

public class ForgotPasswordActivity extends AppCompatActivity implements View.OnClickListener{

    private void submit() {
        accountService.forgotPassword();
    }
}

凌空请求完成时,我想要更新的用户界面我 activity 。怎么这考虑到这一个异步的请求?我能从 AccountService 类中调用的方法我 activity 吗?谢谢你的帮助

解决方法 1:

将listener对象传递给 AccountService,然后发送通信成功或错误到 activity

尝试按下面 (你不应该忽视 layout 到 AccountService,会造成一些不必要的问题)

public class ForgotPasswordActivity extends AppCompatActivity 
                 implements View.OnClickListener,   
                                   AccountServiceCallback{

       private void submit() {
                AccountService.forgotPassword("email@123.com", this);
       }


       @Override
       public void onClick(View v) {

       }

      @Override
      public void onResponse(JSONArray response) {
             // UPDATE UI as per on response requirement
      }

      @Override
      public void onErrorResponse(VollyError error) {
             // UPDATE UI as per response flow
      }
}

public class AccountService {

    public static void forgotPassword(Context c, String email, final    
                       AccountServiceCallback callback) {

           String url = "myUrl";

           JsonArrayRequest request = new JsonArrayRequest(url,
                            new Response.Listener<JSONArray>() {
                      @Override
                      public void onResponse(JSONArray response) {
                             // done
                             callback.onResponse(response);
                      }
            }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
                callback.onErrorResponse(error);
           }
       });

      Volley.newRequestQueue(c).add(request);

     }

   interface AccountServiceCallback {
       public void onResponse(JSONArray response);
       public void onErrorResponse(VollyError error);
   }
 }
官方微信
官方QQ群
31647020