今天做项目,有一个方法,里面调用了一个后台接口更新user信息,这个方法很多地方都会用到,然后我就把他提出来放到了application中,然后就发现了一个问题,因为那个方法中是异步调用接口,获得到结果之后无法通知给调用接口的activity(这里我们称为调用者),这时候,就需要使用接口回调了。
所谓的接口回调,就是A让B去处理一件事,但是B现在在忙,B跟A说等我忙完就处理这件事,处理好了我通知你。
下面上代码实践一下
第一步:定义接口userinfoInterface
public interface UserinfoInterface { void getUserInfo(UserInfo userInfo); }第二步:在application中定义方法getUserInfo()并将请求结果放入回调
public void getUserInfo(final UserinfoInterface userinfoInterface){ OkHttpUtils.post().url(HttpUtils.PERSONALINFO_URL).addParams("user_id",application.userInfo.getId()+"").build().execute(new MobileCallBack(){ @Override public void onError(Call call, Exception e, int id) { super.onError(call, e, id); } @Override public void onResponse(Mobile response, int id) { super.onResponse(response, id); if (response.getCode()==100){ userInfo=gson.fromJson(gson.toJson(response.getResult()).toString(),new TypeToken<UserInfo>(){}.getType()); SPUtils.setStringPreferences(getApplicationContext(),"Reading","UserInfo",gson.toJson(userInfo)); userinfoInterface.getUserInfo(userInfo); } } }); }
第三步:调用application中的方法去更新user,因为这个类实现了userinfoInterface接口,所以把这个this当作参数传递过去,并且实现getUserInfo()方法去处理结果
ReadingApplication.getApplication().getUserInfo(this);@Override
public void getUserInfo(UserInfo userInfo) { this.userInfo=userInfo; }第三步也可以这样写:
ReadingApplication.getApplication().getUserInfo(new userInfoInterface(){
@Override
public void getUserInfo(UserInfo userInfo){
this.userInfo=userinfo;
}
});
其实android中好多地方都用到了接口回调,比如说最基本的按钮的点击事件,ui的事件处理方面等等。