zoukankan      html  css  js  c++  java
  • 20160127_Android程序完全退出的方法

    Android程序完全退出的方法

      综合比较各种应用程序退出的方法,总结下述最优策略。使应用程序完全退出总共分3步:

    • finish所有Activity
    • 关闭所有后台进程
    • 应用程序退出

      代码如下:

     1 /**
     2  * 退出应用程序
     3  * @param context
     4  */
     5  @SuppressWarnings("deprecation")
     6  public void AppExit(Context context){
     7    try {
     8      finishAllActivity();
     9         ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    10         activityMgr.restartPackage(context.getPackageName());
    11         System.exit(0);
    12     } catch (Exception e) {
    13         e.printStackTrace();
    14     }
    15 }
     1 private static Stack<Activity> activityStack;
     2 /**
     3 * 结束所有Activity
     4 * @return
     5 */
     6 public void finishAllActivity() {
     7     for (int i = 0, size = activityStack.size(); i < size; i++) {
     8       if(activityStack.get(i)!=null){
     9           activityStack.get(i).finish();
    10       }
    11       activityStack.clear();
    12     }
    13 }

    注解:

    1. finish所有Activity:遍历activityStack,逐个finish;
    2. 关闭所有后台进程:
      ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
      activityMgr.restartPackage(context.getPackageName());

      (1) 需要添加关闭应用程序的权限:
        <uses-permission android:name="android.permission.RESTART_PACKAGES" />
      (2) API:

        public void restartPackage (String packageName)

        This method was deprecated in API level 8.
        This is now just a wrapper for killBackgroundProcesses(String); the previous behavior here is no longer available to applications because it allows them to break other applications by removing their   alarms, stopping their services, etc. 

       

        public void killBackgroundProcesses (String packageName)

        Have the system immediately kill all background processes associated with the given package. This is the same as the kernel killing those processes to reclaim memory; the system will   take care of restarting these processes in the future as needed.

        You must hold the permission KILL_BACKGROUND_PROCESSES to be able to call this method.

        Parameters
        The name of the package whose processes are to be
      
      
    3. 应用程序退出:System.exit(0)
  • 相关阅读:
    02020_正则表达式练习
    SSM框架——以注解形式实现事务管理
    Spring + Mybatis 使用 PageHelper 插件分页
    使用Mozilla Firefox插件RestClient测试Http API接口
    Maven学习 (四) 使用Nexus搭建Maven私服
    BigDecimal类型比较大小
    Mybatis 的分页插件PageHelper-4.1.1的使用
    svn设置提交忽略某些文件或文件夹
    HTML编辑器 图片粘贴上传,实现图文粘贴,图片自动上传
    java 支持 超大上G,多附件上传方案
  • 原文地址:https://www.cnblogs.com/wanlong/p/5163259.html
Copyright © 2011-2022 走看看