温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

完全关闭App的两种做法

发布时间:2020-07-27 08:28:02 来源:网络 阅读:601 作者:一剑围城 栏目:开发技术

  做项目的时候,涉及到一个注销登录的过程,这时候需要关闭之前打开的所有Activity。仅finish当前Activity显然是不够的,需要把返回栈中的Activity一个个销毁。我实践过的方法有两种:

1、基础类BaseActivity中注册广播接收器,接受关闭所有Activity的广播

2、基础类BaseActivity中将Activity加入一个集合中,并提供一个静态finishAll的方法统一关闭

备注:App中所有Activity直接或间接继承自BaseActivity。 


一、使用广播接收器发送统一销毁广播

ExitAppReceiver 广播接收器代码:

public class ExitAppReceiver extendsBroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
 
       String action = intent.getAction();
       if (action.equals("exit_app")){
           if (context != null){
                if (context instanceofActivity){
                    ((Activity)context).finish();
                }
                if (context instanceofService){
                   ((Service)context).stopSelf();
                }
           }
       }
    }
}

 BaseActivity中注册销毁广播接收器:

public class BaseActivity extendsAppCompatActivity {
   private static final String TAG = "BaseActivity";
   private ExitAppReceiver exitAppReceiver;
 
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       registerExitAppReceiver();//注册
    }
 
   @Override
   protected void onDestroy() {
       super.onDestroy();
       unRegisterExitAppReceiver();//销毁
    }
 
   private void registerExitAppReceiver(){
       IntentFilter filter = new IntentFilter();
       filter.addAction("exit_app");
       exitAppReceiver = new ExitAppReceiver();
       registerReceiver(exitAppReceiver, filter);
    }
 
   private void unRegisterExitAppReceiver(){
       unregisterReceiver(exitAppReceiver);
    }
}


发送关闭所有Activity广播:

  Intent intent = new Intent("exit_app");

  sendBroadcast(intent);

 

、采用ActivityCollector(方法参考郭霖《第一行代码》第2版

ActivityCollector源码

public class ActivityCollector {
   public static List<Activity> list = new ArrayList<>();
 
   public static void addActivity(Activity activity){
       list.add(activity);
    }
 
   public static void removeActivity(Activity activity){
       list.remove(activity);
    }
 
   public static void finishAllActivity(){
       for (Activity activity :list) {
           if (!activity.isFinishing()){
                activity.finish();
           }
       }
    }
}

 

BaseActivity中添加和移除:

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       ActivityCollector.addActivity(this);
    }
 
   @Override
   protected void onDestroy() {
       super.onDestroy();
       ActivityCollector.removeActivity(this);
    }


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI