zoukankan      html  css  js  c++  java
  • 采用FLAG_ACTIVITY_CLEAR_TOP退出整个程序(多activity)

    问题: 
    多activity中退出整个程序,例如从A->B->C->D,这时我需要从D直接退出程序。 
    网上资料:{ 
    finish()和system(0)都只能退出单个activity。杀进程等的等方式都不行~~~ 
    解决问题: 
    我们知道Android的窗口类提供了历史栈,我们可以通过stack的原理来巧妙的实现,这里我们在D窗口打开A窗口时在Intent中直接加入标志Intent.FLAG_ACTIVITY_CLEAR_TOP,再次开启A时将会清除该进程空间的所有Activity。 
    在D中使用下面的代码: 

    Java代码  收藏代码
    1. Intent intent = new Intent();   
    2. intent.setClass(D.this, A.class);  
    3. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置  
    4. startActivity(intent);  
    5. finish();//关掉自己  


    在A中加入代码: 

    Java代码  收藏代码
    1. //Override  
    2. protected void onNewIntent(Intent intent) {  
    3. // TODO Auto-generated method stub  
    4. super.onNewIntent(intent);  
    5. //退出  
    6.         if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0) {  
    7.                finish();  
    8.         }  
    9. }  



    A的Manifest.xml配置成android:launchMode="singleTop" 
    原理总结: 
    一般A是程序的入口点,从D起一个A的activity,加入标识Intent.FLAG_ACTIVITY_CLEAR_TOP这个过程中会把栈中B,C,都清理掉。因为A是android:launchMode="singleTop" 
    不会调用oncreate(),而是响应onNewIntent()这时候判断Intent.FLAG_ACTIVITY_CLEAR_TOP,然后把A finish()掉。 
    栈中A,B,C,D全部被清理。所以整个程序退出了。 

    诗帆个人补充: 
    1.可以把A设置成不可见的Acitivity(方法见下面),然后在它的onCreate方法里跳转到“真正”的载入界面 
    就可以实现在D中点退出程序按钮时看上去立即退出程序的效果 
    2.A必须是程序启动的第一个Activity才能起到这种立即退出的效果,因为Intent.FLAG_ACTIVITY_CLEAR_TOP只会把目标Activity的“上面”的Activity清理掉,而如果目标Activity的“下面”还有Activity(换句话说,目标Activity不在栈底),则finish后只会到他下面的那个Activity,而不是立即退出的效果了 
    3.不可见Activity 
    在项目的AndroidManifest.xml文件中相应的Activity标签中添加这样一行: 
    android:theme=”@android:style/Theme.NoDisplay” 
    这样一来,当这个Activity启动的时候,就不会显示出界面了。
     


    Android 2.2完全退出程序, 使用广播机制 
    http://www.iteye.com/topic/1112269

  • 相关阅读:
    第八章 多线程编程
    Linked List Cycle II
    Swap Nodes in Pairs
    Container With Most Water
    Best Time to Buy and Sell Stock III
    Best Time to Buy and Sell Stock II
    Linked List Cycle
    4Sum
    3Sum
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/leihupqrst/p/3484908.html
Copyright © 2011-2022 走看看