当前位置:操作系统 > 安卓/Android >>

Android 怎么退出整个应用程序?

在开发andorid程序的时候,难免会牵扯到退出整个应用程序的情况,怎么完全退出呢?请参阅下面的关键代码:


[java] import java.util.LinkedList; 
import java.util.List; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.Application; 
import android.content.DialogInte易做图ce; 
import android.content.Intent; 
 
public class SysApplication extends Application { 
    private List<Activity> mList = new LinkedList<Activity>(); 
    private static SysApplication instance; 
 
    private SysApplication() {   
    } 
 
    public synchronized static SysApplication getInstance() { 
        if (null == instance) { 
            instance = new SysApplication(); 
        } 
        return instance; 
    } 
 
    // add Activity  
    public void addActivity(Activity activity) { 
        mList.add(activity); 
    } 
 
    public void exit() { 
        try { 
            for (Activity activity : mList) { 
                if (activity != null) 
                    activity.finish(); 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally { 
            System.exit(0); 
        } 
    } 
 
    @Override 
    public void onLowMemory() { 
        super.onLowMemory();     
        System.gc(); 
    } 
 

import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.DialogInte易做图ce;
import android.content.Intent;

public class SysApplication extends Application {
 private List<Activity> mList = new LinkedList<Activity>();
 private static SysApplication instance;

 private SysApplication() { 
 }

 public synchronized static SysApplication getInstance() {
  if (null == instance) {
   instance = new SysApplication();
  }
  return instance;
 }

 // add Activity
 public void addActivity(Activity activity) {
  mList.add(activity);
 }

 public void exit() {
  try {
   for (Activity activity : mList) {
    if (activity != null)
     activity.finish();
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   System.exit(0);
  }
 }

 @Override
 public void onLowMemory() {
  super.onLowMemory(); 
  System.gc();
 }

}在每个Activity的onCreate方法中添加类似代码:


[java] public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);      
    SysApplication.getInstance().addActivity(this); 

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);  
  SysApplication.getInstance().addActivity(this);
 }


在需要退出程序的时候,调用:


[java] SysApplication.getInstance().exit(); 
SysApplication.getInstance().exit();


简而言之,通过单例模式把每个Activity 的引用添加到一个全局链表中,每次退出程序调用System.exit(0)时,先调用链表中Activity 的finish方法

摘自 心灵净土

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,