我在最新的Android应用程序中使用Retrofit实现了Facebook登录。在SplashActivity和LoginActivity中,我想发出我的POST请求:
FacebookLoginInfo facebookLoginInfo = new FacebookLoginInfo(token);
Call<User> call = ApiManager.getService().authenticateFacebookUser(facebookLoginInfo);
call.enqueue(userCallback);
FacebookLoginInfo是一个带有Facebook访问令牌的简单POJO。 ApiManager是我服务的单例类。
我的问题是在SplashActivity和LoginActivity中userCallback是重复的。是否有最佳实践只定义一次此回调?
用户回调的定义:
private Callback<User> mUserCallback = new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
dismissProgressDialog();
int statusCode = response.code();
if (statusCode == 200) {
User user = response.body();
Log.e(LOG_TAG, "user: " + user.toString());
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(Global.EXTRA_USER, user);
startActivity(intent);
} else if (statusCode == 400) {
Toast.makeText(LoginActivity.this, getString(R.string.error_token_required), Toast.LENGTH_SHORT).show();
} else if (statusCode == 403) {
Toast.makeText(LoginActivity.this, getString(R.string.error_invalid_token), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
dismissProgressDialog();
t.printStackTrace();
Toast.makeText(LoginActivity.this, getString(R.string.error_call_failed), Toast.LENGTH_SHORT).show();
}
};
答案 0 :(得分:0)
您可以创建一个名为UserCallback的类来实现Callback,并在您想要的地方使用它。
在你的情况下:
public class UserCallback implements Callback<EventResponseList> {
@Override
public void onResponse(Call<User> call, Response<User> response) {
dismissProgressDialog();
int statusCode = response.code();
if (statusCode == 200) {
User user = response.body();
Log.e(LOG_TAG, "user: " + user.toString());
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(Global.EXTRA_USER, user);
startActivity(intent);
} else if (statusCode == 400) {
Toast.makeText(LoginActivity.this, getString(R.string.error_token_required), Toast.LENGTH_SHORT).show();
} else if (statusCode == 403) {
Toast.makeText(LoginActivity.this, getString(R.string.error_invalid_token), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
dismissProgressDialog();
t.printStackTrace();
Toast.makeText(LoginActivity.this, getString(R.string.error_call_failed), Toast.LENGTH_SHORT).show();
}
}
当你想要使用它时:
FacebookLoginInfo facebookLoginInfo = new FacebookLoginInfo(token);
Call<User> call = ApiManager.getService().authenticateFacebookUser(facebookLoginInfo);
call.enqueue(new UserCallback());