前言
在大多數(shù)APP中可能會(huì)碰到這樣一個(gè)需求,用戶點(diǎn)擊下一步、下一步后有一個(gè)頁面需要登錄才能查看,在輸入賬號(hào)和密碼,登錄上去后需要再次跳轉(zhuǎn)到原來的頁面。在之前小冷想了很多方法也實(shí)現(xiàn)了但是比較繁瑣,直到看到CSDN一篇簡(jiǎn)短的文章覺得非常好,小冷在此記錄一下。需要粘貼部分代碼的點(diǎn)我查看原文
登錄跳轉(zhuǎn)流程
從A界面跳轉(zhuǎn)到B界面,判斷是否需要登錄,需要登錄時(shí),記錄下B界面的全類名,通過intent傳遞給LoginActivity,不需要登錄直接跳轉(zhuǎn)到B界面。等登錄成功后檢查獲取到的intent中的全類名,通過反射跳轉(zhuǎn)到之前記錄的B界面。
登錄跳轉(zhuǎn)流程
代碼示例
A跳轉(zhuǎn)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()) {//修改為自己的判斷登錄狀態(tài)方法
ComponentName componentName = new ComponentName(context, LoginActivity.class);
intent.putExtra("className", intent.getComponent().getClassName());
intent.setComponent(componentName);
super.startActivity(intent);
} else {
super.startActivity(intent);
}
}
LoginActivity跳轉(zhuǎn)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();
}
小結(jié)
把上面兩個(gè)方法放在BaseActivity內(nèi),即可輕松實(shí)現(xiàn)需求。兩個(gè)方法最主要用到ComponentName這個(gè)類和反射方式獲取類名這兩個(gè)關(guān)鍵點(diǎn)