实际工作中遇到一个需求,点击头部通知进入APP某页面,点击返回键直接跳转到主页
1.新建一个类作为活动管理器 添加activity到堆栈 通过获取activity是否存在可实现操作
public class AppManager {
private static Stack<Activity> activityStack; private static AppManager mAppManager; private AppManager() { } public static AppManager getInstance() { if (mAppManager == null) { synchronized (AppManager.class) { if (mAppManager == null) { mAppManager = new AppManager(); } } } return mAppManager; } /** * 添加activity到堆栈 * * @param activity */ public void addActivity(Activity activity) { if (activityStack == null) { activityStack = new Stack<>(); } activityStack.add(activity); } /** * 获取activity是否存在 */ public boolean currentActivity(Class<?> cls) { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { return true; } } return false; }
2.在相应得activity操作
返回键
case R.id.layout_base_back: if(!AppManager.getInstance().currentActivity(MainActivity.class)){ startActivity(new Intent(this,MainActivity.class)); } finish(); break;
手机返回键
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if(!AppManager.getInstance().currentActivity(MainActivity.class)){ startActivity(new Intent(this,MainActivity.class)); } finish(); return true; } return super.onKeyDown(keyCode, event); }