如何在retrofit2拦截器内启动登录活动?使用dagger2注入依赖性,是否有最佳实践? 像这样说 - 我在LoginMvp.View mview上得到空指针。
private final SharedPreferences preferences;
@Inject LoginMvp.View mview;
private String token;
@Inject
public AuthInterceptor(SharedPreferences preferences) {
this.preferences = preferences;
}
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
Request request = builder.build();
Response response = chain.proceed(request);
if (response.code() == 401) {
//start login activity
login();
}
}
//should call start loginActivity via intent and call finish
public void logout() {
mview.showLoginScreen();
}
答案 0 :(得分:0)
您可以在
的“应用程序上下文”中创建应用程序上下文的静态对象。public class App extends Application {
public static App context;
@Override
public void onCreate() {
super.onCreate();
context = this;
}
}
然后将此类在AndroidManifest中注册为<application android:name="">
然后在您的 mview.showLoginScreen()方法中,对应用程序上下文进行空检查,如果不为空,则将登录活动称为
Intent intent = new Intent(App.context, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
App.context.startActivity(intent)