alltolove 发表于 2017-9-22 06:19:20

android手机编程2.6

把项目中所有的文件都改为继承字BaseActivity这个类,然后在主文件mainactivity.java旁边新建个java类BaseActivitypackage com.example.xinwei.lifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

/**
* Created by xinwei on 2017/9/21.
*/

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Log.i("BaseActivity",getClass().getSimpleName());
      ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy() {
      super.onDestroy();
      ActivityCollector.removeActivity(this);
    }
}

然后再新建个ActivityCollector工具类文件package com.example.xinwei.lifecycle;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;

/**
* Created by xinwei on 2017/9/22.
*/

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

这样就可以很方便的释放空间了。然后将normal_layout.xml文件修改为:<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.xinwei.lifecycle.NormalActivity">
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="finishAll"
    android:onClick="click"/>
</android.support.constraint.ConstraintLayout>

NormalActivity.java修改为package com.example.xinwei.lifecycle;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class NormalActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.normal_layout);
    }
    public void click(View v){
      ActivityCollector.finishAll();
    }
}

进入NormalActivity这个活动后就可以直接退出整个程序了,效果图:

页: [1]
查看完整版本: android手机编程2.6