不知道大家在写 Android 的时候有没有遇到过这样的一个疑惑:当你在重写 onDestry() 的方法时,有没有犹豫过,我们自己的方法,是应该放在 super.onDestroy() 方法的上面呢?还是应该放在 super.onDestroy() 方法的下面呢?如下所示:

@Override
protected void onDestroy() {//是将我们的方法放在这呢?super.onDestroy();//还是将我们的方法放在这呢?
}

带着这样的一个疑惑,我踏上了,解惑之旅!

1. 回头学习一下 super 关键字

super 是 Java 中的一个关键字,指代父类,用于调用父类中的普通方法和构造方法。 在 Java 中子类可以继承父类中所有可访问的数据域和方法,但不能继承父类中的构造方法,所以需要利用 super 来调用父类中的构造方法。

public class Father {    public Father() {System.out.println("I'm father, I have a car.");}
}public class Son extends Father{public Son() {super();System.out.println("I'm son, my father will send him car to me.");}
}public class JereTest {public static void main(String[] args) {System.out.println("print son!");Son son = new Son();}
}输出结果:
print son!
I'm father, I have a car.
I'm son, my father will send him car to me.

2. 弄明白 super.onDestroy() 做了什么

当我们知道 super.onDestroy() 做了什么的时候,就不用疑惑自己的方法是放在 super.onDestroy() 方法前,还是 super.onDestroy() 方法后了。

首先,根据官方文档的介绍,onDestroy() 是在活动被销毁之前执行最后的清理。这可能是因为活动正在完成(有人在其上调用了 finish() 方法),也可能是因为系统为了节省空间而临时销毁了活动的这个实例。您可以使用 isFinishing() 方法来区分这两个场景。
注意:不要指望调用此方法来保存数据! 例如,如果一个活动正在内容提供者中编辑数据,那么这些编辑应该在 onPause() 或 onSaveInstanceState(Bundle) 中提交,而不是在这里提交。此方法通常用于释放与某个活动关联的线程等资源,以便被销毁的活动在其应用程序的其余部分仍在运行时不会留下这些资源。在某些情况下,系统只会在不调用此方法(或任何其他方法)的情况下终止活动的宿主进程,因此不应该使用它来做一些在进程结束后仍然存在的事情。
派生类必须通过超类来调用此方法的实现。如果没有,则抛出异常。

接着,我们到 Activity.java 中,查看 onDestroy() 方法究竟做了啥,如下:

/*** Perform any final cleanup before an activity is destroyed.  This can* happen either because the activity is finishing (someone called* {@link #finish} on it), or because the system is temporarily destroying* this instance of the activity to save space.  You can distinguish* between these two scenarios with the {@link #isFinishing} method.** <p><em>Note: do not count on this method being called as a place for* saving data! For example, if an activity is editing data in a content* provider, those edits should be committed in either {@link #onPause} or* {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to* free resources like threads that are associated with an activity, so* that a destroyed activity does not leave such things around while the* rest of its application is still running.  There are situations where* the system will simply kill the activity's hosting process without* calling this method (or any others) in it, so it should not be used to* do things that are intended to remain around after the process goes* away.** <p><em>Derived classes must call through to the super class's* implementation of this method.  If they do not, an exception will be* thrown.</em></p>** @see #onPause* @see #onStop* @see #finish* @see #isFinishing*/@CallSuperprotected void onDestroy() {if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);mCalled = true;// dismiss any dialogs we are managing.// dismiss 我们管理着的所有对话框if (mManagedDialogs != null) {final int numDialogs = mManagedDialogs.size();for (int i = 0; i < numDialogs; i++) {final ManagedDialog md = mManagedDialogs.valueAt(i);if (md.mDialog.isShowing()) {md.mDialog.dismiss();}}mManagedDialogs = null;}// close any cursors we are managing.// 关闭我们正在管理的 Cursorsynchronized (mManagedCursors) {int numCursors = mManagedCursors.size();for (int i = 0; i < numCursors; i++) {ManagedCursor c = mManagedCursors.get(i);if (c != null) {c.mCursor.close();}}mManagedCursors.clear();}// Close any open search dialog// 关闭任何打开的搜索对话框if (mSearchManager != null) {mSearchManager.stopSearch();}if (mActionBar != null) {mActionBar.onDestroy();}//调用Application中的onActivityDestroyed方法,将该Activity从栈中删除。dispatchActivityDestroyed();notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_STOP);}

从上方的代码可以看出,super.onDestroy() 干了三件事:

  1. dismiss 所有我们管理着的 Dialog。
  2. 关闭我们正管理着的 Cursor。
  3. 关闭任何打开着的搜索对话框
  4. 将该Activity从栈中删除

现在知道了 onDestroy() 方法做了什么事情了吧,所以为了防止空异常的出现,我们需要将 ‘我们自己的方法’ 放在 super.onDestroy() 方法上面,比如:

@Override
protected void onDestroy() {// 我们自己的方法。super.onDestroy();

总结

在重写 onDestroy() 方法时,为了防止出现空异常,我们需要将我们的方法放在 super.onDestroy() 方法上面(但目前我还没遇到到重写 onDestroy() 方法出现空异常)。

顺带记录一下重写 Activity 生命周期的正确姿势:

public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_test);//我们自己的方法}@Overrideprotected void onStart() {super.onStart();//我们自己的方法}@Overrideprotected void onResume() {super.onResume();//我们自己的方法}@Overrideprotected void onRestart() {super.onRestart();//我们自己的方法}/***  在onPause() onStop() onDestroy() *  这三种方法中需要将我们自己的方法放在 super 方法之上。**/@Overrideprotected void onPause() {//我们自己的方法super.onPause();}@Overrideprotected void onStop() {//我们自己的方法super.onStop();}@Overrideprotected void onDestroy() {//我们自己的方法super.onDestroy();}
}

个人观点,如有错误,欢迎指正,感谢!

Android 如何正确的重写 onDestroy() 方法相关推荐

  1. android phone恢复出厂设置,Android手机正确恢复出厂设置方法

    Android手机正确恢复出厂设置方法 作为一款智能操作系统,Android也内置了许多其他智能操作系统共有的功能,比如每部手机都必备的恢复出厂设置.那么Android手机该如何设置,才能让它正确的恢 ...

  2. android使用menu需要重写的方法,Android – 正确使用invalidateOptionsMenu()

    我一直在关注invalidateOptionsMenu() ,我知道它的作用. 但是我想不出这个方法可能有用的任何现实生活中的例子. 我的意思是,例如,假设我们想要为ActionBar添加一个新的Me ...

  3. Android自定义控件:imageview重写onMeasure方法实现图片按指定比例显示,拉伸永不变形,解决屏幕适配问题

    使用ImageView会遇到的问题 在Android应用中,都少不了图片的显示,ImageView,轮播图,ViewPager等等,很多都是来显示图片的,比如一个广告条的轮播效果,参看博客:广告条效果 ...

  4. android studio提示要重写的方法,Android Studio 重写方法时参数命名异常

    kuangbin_SegTree M (HDU 4553) put my gezi这句话不得不说我看了好几秒才反应过来什么意思(你咋不上天呢 目测了一下也是区间合并 但是是成段更新的区间合并 但是!我 ...

  5. android espresso跨程序,在Espresso Android中正确使用IdlingResource的方法

    我正在用Espresso编写UI测试.应用程序与服务器紧密配合,因此在许多情况下,我需要等待任意一个值进行计算,或者获取和显示数据.Espresso建议使用IdlingResource. 我的Idli ...

  6. android 退出应用没有走ondestory方法,Android退出应用最优雅的方式(改进版)

    我们先来看看几种常见的退出方法(不优雅的方式) 一.容器式 建立一个全局容器,把所有的Activity存储起来,退出时循环遍历finish所有Activity import java.util.Arr ...

  7. java如何重写onestring,44 java toString 方法 重写equals 方法

    package com.wjl.zy131227; /** * 打印对象 * toString 方法 * @author Administrator * */ public class ToStrin ...

  8. android播放MP3文件的解决方法

    在res文件夹中新建一个文件夹,命名为raw.在里面放入我们需要的音频文件. // 根据资源创建播放器对象 为了方便,我直接放在MainActivity.java的onCreate中player = ...

  9. android 为什么不调用onDestroy方法关闭activity

    前天有个同学突然咨询我,说关闭android的activity,为什么不直接调用ondestroy方法,而是要调用activity.finish(). 我这里总结下我的理解: 1.我们知道onDest ...

最新文章

  1. 欧蓝德 (660) -(警车内被乔丹体育)_几款豪华SUV的油耗与空间的巅峰对决!欧蓝德还是奇骏...
  2. ML之xgboost:利用xgboost算法(特征筛选和GridSearchCV)对数据集实现回归预测
  3. 【CyberSecurityLearning 15】VLAN技术与Trunk
  4. 《Head First设计模式》批注系列(一)——观察者设计模式
  5. 增删改查(curd)
  6. 用人工智能来喂鱼:喂多少智能算法说了算
  7. 端午安康 | 6月14日 星期一 | B站首个破亿视频诞生;荣耀50系列预约人数超百万;贝索斯太空船票拍出2800万美元...
  8. iPhone近两个财季为苹果带来1135亿美元营收 同比增长33%
  9. 【FFMPEG系列】之windows下编译FFMPEG篇----之二(MSYS2)
  10. 阿里巴巴开源离线同步工具 DataX3.0 介绍
  11. 面试出现频率超高的一道算法题
  12. linux页表创建与更新
  13. 微软雅黑在IE中显示为宋体
  14. Ubuntu16 e1000e驱动安装
  15. Gap Statistic 间隔统计量
  16. 方舟手游服务器延迟太高怎么办,方舟手机版服务器延迟太高 | 手游网游页游攻略大全...
  17. 内与外的困惑:找出System进程占用100%CPU的元凶
  18. ssl免费证书获取,并在nginx服务器上安装ssl证书,以及docker安装nginx需注意的细节。
  19. 群晖Docker部署MySQL服务
  20. 小米误删userdata分区,userdata分区无法还原,安卓误删分区,且能进twrp,刷机卡米的情况,重新分区教程

热门文章

  1. Explain字段解释——ref
  2. JavaScript 删除数组中指定元素(5种方法)
  3. RGB图像灰度直方图的绘制
  4. MySQL——02【基本CRUD操作】
  5. 情人节特献:有心之函数必然就有分手函数
  6. 如何在C/C++中定义坐标函数gotoxy()并灵活运用之
  7. 量化交易平台有什么限制吗?
  8. 12行贪吃蛇html,贪吃蛇大作战无敌版
  9. HTTPS成“新宠”,七牛云推出SSL证书免费申请 并宣布HTTPS调价
  10. strong man