概述
使用 ARouter 路由框架优雅地实现登录拦截功能。
前言
一个应用中有许多页面,有些页面是无需登录的(游客模式),有些页面是需要登录才能看的,当我们进行页面跳转时会先判断用户是否登录。如果已经登录,则正常跳转;如果没有登录,则跳转到登录页面先登录。这样的操作,大家应该都很熟悉吧。一般情况下,我们的逻辑是这样的:
1 2 3 4 5 6 7
| if (TextUtils.isEmpty(token)) { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); } else { Intent intent = new Intent(this, OrderActivity.class); startActivity(intent); }
|
上面的做法需要在每一个目标页面重复做登录检查,这样设计的扩展性并不友好。在这里介绍阿里的 ARouter 路由框架,可以更加优雅地实现登录拦截功能。
使用方法
SDK 初始化
SDK 集成步骤:ARouter。
拦截器的使用
登录拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
@Interceptor(name = "login", priority = 3) public class LoginInterceptorImpl implements IInterceptor {
@Override public void process(Postcard postcard, InterceptorCallback callback) { String path = postcard.getPath(); if (isNotLogin()) { switch (path) { case RouterHub.PATH_LOGIN: case RouterHub.PATH_MAIN: callback.onContinue(postcard); break; default: callback.onInterrupt(null); break; } } else { callback.onContinue(postcard); }
}
@Override public void init(Context context) { }
private boolean isNotLogin() { return <判断是否登录>; }
}
|
路由跳转的回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
public class LoginNavigationCallbackImpl implements NavigationCallback {
@Override public void onFound(Postcard postcard) {
}
@Override public void onLost(Postcard postcard) {
}
@Override public void onArrival(Postcard postcard) {
}
@Override public void onInterrupt(Postcard postcard) { String path = postcard.getPath(); Bundle bundle = postcard.getExtras(); ARouter.getInstance().build(RouterHub.PATH_LOGIN) .with(bundle) .withString(RouterHub.PATH, path) .navigation(); } }
|
启动 Activity
1 2 3
| ARouter.getInstance().build(RoutePath.PATH_SECOND) .withString("msg", "ARouter 传递过来的需要登录的参数 msg") .navigation(this, new LoginNavigationCallbackImpl());
|
这样就能实现页面的登录拦截了。