超详细的Activity与Fragment的生命周期图,可能你们会说你这篇文章也太水了吧。就这么一个破图。但是我以为它写的很详细,有些方法是哪些状况下会运行,哪些状况不会运行,写的一清二楚。不知道你们能回答对多少。java
强烈建议你们把图片右键另存到本地,而后本地放大看。看的更清楚!!bash
好了咱们先来逐个看看Activity中一些平时不经常使用的函数:ide
onPostCreate是指onPostCreate方法是指onCreate方法完全执行完毕的回调,onPostResume同理.函数
咱们先来看onUserInteraction:布局
/**
* Called whenever a key, touch, or trackball event is dispatched to the
* activity. Implement this method if you wish to know that the user has
* interacted with the device in some way while your activity is running.
*
* <p>All calls to your activity's {@link #onUserLeaveHint} callback will * be accompanied by calls to {@link #onUserInteraction}. * * activity不管分发按键事件、触摸事件或者轨迹球事件都会调用Activity#onUserInteraction()。 * 若是你想知道用户用某种方式和你正在运行的activity交互,能够重写Activity#onUserInteraction()。 * 全部调用Activity#onUserLeaveHint()的回调都会首先回调Activity#onUserInteraction()。 */ 复制代码
activity在分发各类事件的时候会调用该方法,注意:启动另外一个activity,Activity#onUserInteraction()会被调用两次,一次是activity捕获到事件,另外一次是调用Activity#onUserLeaveHint()以前会调用Activity#onUserInteraction()。ui
那必定有人会问这个方法咱们有什么用处呢。咱们看到咱们能够用这个方法来监控用户有没有与当前的Activity进行交互,那咱们就能够针对这个来假设场景,有个APP要求N分钟后用户没有进行操做,那就自动出来动态壁纸,或者进行锁屏界面,或者跳到登陆界面从新登陆等!那咱们只须要写个倒计时,而后每次调用了onUserInteraction方法,就把时间重置便可。。多方便!!this
咱们再看onUserLeaveHint:spa
/**
* Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice.
* For example, when the user presses the Home key, {@link #onUserLeaveHint} will be called, but
* when an incoming phone call causes the in-call Activity to be automatically brought to the foreground,
*{@link #onUserLeaveHint} will not be called on the activity being interrupted.
*
* 当用户的操做使一个activity准备进入后台时,此方法会像activity的生命周期的一部分被调用。例如,当用户按下Home键,
* Activity#onUserLeaveHint()将会被回调。可是当来电致使来电activity自动占据前台,Activity#onUserLeaveHint()将不会被回调。
*/
复制代码
用户手动离开当前activity,会调用该方法,好比用户主动切换任务,短按home进入桌面等。系统自动切换activity不会调用此方法,如来电,灭屏等。code
咱们通常监听返回键,确定是重写onKeyDown方法,可是Home键和Menu键就很差监听了。可是有了这个方法。咱们能够作统一的监听了。好比要监听用户点了Home键跳回到桌面后。咱们要求这个APP自动跳转到解锁界面。咱们只要在这里作监听出来便可。cdn
onContentChanged()是Activity中的一个回调方法,当Activity的布局改动时,即setContentView()或者addContentView()方法执行完毕时就会调用该方法。那咱们能够用来干吗呢。好比咱们平时写的findViewById方法,也能够统一放到这个方法下:
@Override
public void onContentChanged() {
super.onContentChanged();
mGalleryButton = (Button) findViewById( R.id.button1 );
mEditButton = (Button) findViewById( R.id.button2 );
}
复制代码
onAttachedToWindow是在第一次onDraw前调用的。也就是咱们写的View在没有绘制出来时调用的,但只会调用一次。 好比,咱们写状态栏中的时钟的View,在onAttachedToWindow这方法中作初始化工做,好比注册一些广播等等…… 并且若是要修改window窗口的尺寸,不会在onCreate方法中进行修改,而是在onAttachedToWindow方法中进行修改。 在Android4.0前面,若是想屏蔽Home键事件,还能够在onAttachedToWindow这么写:
@Override
public void onAttachedToWindow() {
// TODO Auto-generated method stub
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
super.onAttachedToWindow();
}
复制代码
只是如今在Android4.0后面这样已经无效了,会报错:
java.lang.IllegalArgumentException: Window type can not be changed after the window is added.
复制代码