未登录跳转登录页 登录后跳转原来页

前言

在大多数APP中可能会碰到这样一个需求,用户点击下一步、下一步后有一个页面需要登录才能查看,在输入账号和密码,登录上去后需要再次跳转到原来的页面。在之前小冷想了很多方法也实现了但是比较繁琐,直到看到CSDN一篇简短的文章觉得非常好,小冷在此记录一下。需要粘贴部分代码的点我查看原文

登录跳转流程

从A界面跳转到B界面,判断是否需要登录,需要登录时,记录下B界面的全类名,通过intent传递给LoginActivity,不需要登录直接跳转到B界面。等登录成功后检查获取到的intent中的全类名,通过反射跳转到之前记录的B界面。


未登录跳转登录页 登录后跳转原来页_第1张图片
登录跳转流程

代码示例

A跳转B(在界面A中写)

Intent intent= new Intent(this,NextActivty.class);
intent.putString("key","value");
startActivityAfterLogin(this,intent);

public void startActivityAfterLogin(Context context,Intent intent) {
    //未登录(这里用自己的登录逻辑去判断是否未登录)
    if (! UserUtils.getLoginStatus()) {//修改为自己的判断登录状态方法
        ComponentName componentName = new ComponentName(context, LoginActivity.class);
        intent.putExtra("className", intent.getComponent().getClassName());
        intent.setComponent(componentName);
        super.startActivity(intent);
    } else {
        super.startActivity(intent);
    }
}

LoginActivity跳转B(在LoginActivity界面中写)

Intent intent= new Intent(this,NextActivty.class);
startActivityAfterLogin(intent);

   public void startActivity(Context context) {
        if (getIntent().getExtras() != null && getIntent().getExtras().getString("className") != null) {
            String className = getIntent().getExtras().getString("className");
            getIntent().removeExtra("className");
            if (className != null && !className.equals(context.getClass().getName())) {
                try {
                    ComponentName componentName = new ComponentName(context, Class.forName(className));
                    startActivity(getIntent().setComponent(componentName));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        finish();
    }

小结

把上面两个方法放在BaseActivity内,即可轻松实现需求。两个方法最主要用到ComponentName这个类和反射方式获取类名这两个关键点

友情链接

csdn登录和跳转判断

你可能感兴趣的:(未登录跳转登录页 登录后跳转原来页)