如何安全的退出一个已开启多个Activity的Android Application
- - 移动开发 - ITeye博客在Android系统中,默认情况下,每开启一个Activity,都在会当前的任务栈中压入一个新的Activity,当我们在一个Application中开发了多个Activity的时候,如果想要退出应用,那么我们需要按多此返回键才能退出...这样就造成用户体验很不好的情况. 那么,怎样做才能让用户在想退出Application的时候,只按一个返回键就能退出呢.
public class MyApplication extends Application { public List<Activity> myApps; @Override public void onCreate() { myApps = new ArrayList<>(); super.onCreate(); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); MyApplication myApplication = (MyApplication) getApplication(); myApplication.myApps.add(this); }
@Override public void onBackPressed() { super.onBackPressed(); MyApplication myApplication = (MyApplication) getApplication(); for (Activity acticity : myApplication.myApps) { acticity.finish(); } }
@Override protected void onDestroy() { super.onDestroy(); MyApplication myApplication = (MyApplication) getApplication(); myApplication.myApps.remove(this); }