首页 > 代码库 > 学习笔记:两个开发过程的小技巧

学习笔记:两个开发过程的小技巧

1.在实际开发中,我们经常会遇到查看当前Activity叫什么名字,是哪个类,当我们去翻阅别的的代码时,真是头疼,所以可已在项目的BaseActivity中写一个得到Activity名称的方法,继承这个Base的Activity的名字都会被打印出来,如下

public class BaseActivity extends AppCompatActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Log.e("className:", getActivityName());    }    private String getActivityName() {        return getClass().getSimpleName();    }} 

运行结果:

技术分享

2.在开发中可能会遇到随时随地退出程序的时候,这时候该怎么处理呢,可以写一个Activity的管理类,想退出时,依次finish掉Activity

public class ActivityControler {    private static List<Activity> activityList = new ArrayList<>();    //添加Actiivty    public static void addActiivty(Activity activity) {        activityList.add(activity);    }    //删除Activity    public static void removeActivity(Activity activity) {        activityList.remove(activity);    }    //退出程序时逐个关闭    public static void removeAllActivity() {        if (!activityList.isEmpty()) {            for (Activity activity : activityList) {                if (!activity.isFinishing())                    activity.finish();            }        }    }}

然后在BaseActivity生命周期中做添加和删除操作

public class BaseActivity extends AppCompatActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Log.e("className:", getActivityName());    }    private String getActivityName() {        return getClass().getSimpleName();    }    @Override    protected void onResume() {        super.onResume();        ActivityControler.addActiivty(this);    }    @Override    protected void onDestroy() {        super.onDestroy();        ActivityControler.removeActivity(this);    }}

如果想在某一个Actiivty中退出程序

public class SecondActivity extends BaseActivity {    private Button mButton;    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_second);        mButton = (Button) findViewById(R.id.button);        mButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                ActivityControler.removeAllActivity();                //android.os.Process.killProcess(android.os.Process.myPid());            }        });    }}

如果想保证程序完全退出,可以在finish掉所有Actiivty之后加上结束进程代码android.os.Process.killProcess(android.os.Process.myPid())

学习笔记:两个开发过程的小技巧