Aru*_*tha 75 android android-activity
我有两个不同的活动.第一个发射第二个.在第二个活动中,我调用System.exit(0)
以强制关闭应用程序,但是第一个活动会自动显示,而不是返回到主屏幕的应用程序.如何避免这种情况,让应用程序返回主屏幕?
Dav*_*ebb 88
简短的回答:打电话moveTaskToBack(true)
给你Activity
而不是System.exit()
.这将隐藏您的应用程序,直到用户想要再次使用它.
更长的答案从另一个问题开始:你为什么要杀死你的申请?
Android操作系统处理内存管理和进程等等,所以我的建议是让Android为您担心.如果用户想要离开您的应用程序,他们可以按"主页"按钮,您的应用程序将有效消失.如果手机需要更多内存,操作系统将终止您的应用程序.
只要您正确地响应生命周期事件,您和用户都不需要关心您的应用程序是否仍在运行.
因此,如果你想隐藏你的应用程序调用moveTaskToBack()
,让Android决定何时杀死它.
小智 53
下面给出了实现此目的的最简单方法(不影响Android的本机内存管理.不涉及进程终止).
使用此Intent启动活动:
Intent intent = new Intent(this, FinActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
Run Code Online (Sandbox Code Playgroud)在目标活动中FinActivity.class
,调用finish()onCreate
.
步骤说明:
您创建一个删除所有其他活动(FLAG_ACTIVITY_CLEAR_TOP)
并删除当前活动的intent .
活动摧毁了自己.另一种方法是,您可以在finActivity中制作闪屏.这是可选的.
Rom*_*Guy 45
你应该考虑不退出应用程序.这不是Android应用程序通常的工作方式.
Dan*_*OMS 20
Android有一个机制来根据其文档安全地关闭应用程序.在退出的最后一个Activity(通常是应用程序启动时首次出现的主Activity)中,只需在onDestroy()方法中放置几行.对System.runFinalizersOnExit(true)的调用可确保在应用程序退出时完成所有对象并收集垃圾.例如:
public void onDestroy() {
super.onDestroy();
/*
* Notify the system to finalize and collect all objects of the
* application on exit so that the process running the application can
* be killed by the system without causing issues. NOTE: If this is set
* to true then the process will not be killed until all of its threads
* have closed.
*/
System.runFinalizersOnExit(true);
/*
* Force the system to close the application down completely instead of
* retaining it in the background. The process that runs the application
* will be killed. The application will be completely created as a new
* application in a new process if the user starts the application
* again.
*/
System.exit(0);
}
Run Code Online (Sandbox Code Playgroud)
最后,Android不会通知HOME键事件的应用程序,因此在按下HOME键时无法关闭应用程序.Android会将HOME键事件保留 给自己,以便开发人员无法阻止用户离开其应用程序.
我用这个方法关闭活动!
public static void closeAllBelowActivities(Activity current) {
boolean flag = true;
Activity below = current.getParent();
if (below == null)
return;
System.out.println("Below Parent: " + below.getClass());
while (flag) {
Activity temp = below;
try {
below = temp.getParent();
temp.finish();
} catch (Exception e) {
flag = false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当您启动第二个活动时,finish()
第一个活动立即:
startActivity(new Intent(...));
finish();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
156492 次 |
最近记录: |