每天都在用Activity,但是确从来没有认真看过Activity的源代码,实属遗憾。今天周末,公司加班,来的比较早,正好看看。
Activity的源码类注释写的非常细致,几乎和官方文档写的一样细致了, 大致的浏览了一遍,就是简单的介绍。但是里面的内容都非常重要,涉及到以下几个方面的内容。
Topics covered here:
- Activity Lifecycle
- Configuration Changes
- Starting Activities and Getting Results
- Saving Persistent State
- Permissions
- Process Lifecycle
看下类声明,继承了一个类,实现了几个接口:
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks
LayoutInflater.Factory这个是和初始化XML文件相关的接口;
Window.Callback这个接口有很多回调方法;
KeyEvent.Callback onKeyDown等回调方法都在这个接口里;
OnCreateContextMenuListener context menu被创建时的回调;
ComponentCallbacks :
看注释:The set of callback APIs that are common to all application components (android.app.Activity
, android.app.Service
, ContentProvider
, and android.app.Application
). 这个接口只有2个方法:onLowMemory,onConfigurationChanged。
再看继承的这个类:
/**
* A ContextWrapper that allows you to modify the theme from what is in the
* wrapped context.
*/
public class ContextThemeWrapper extends ContextWrapper
/**
* Proxying implementation of Context that simply delegates all of its calls to
* another Context. Can be subclassed to modify behavior without changing
* the original Context.
*/
public class ContextWrapper extends Context
/**
* Interface to global information about an application environment. This is
* an abstract class whose implementation is provided by
* the Android system. It
* allows access to application-specific resources and classes, as well as
* up-calls for application-level operations such as launching activities,
* broadcasting and receiving intents, etc.
*/
public abstract class Context
里面还有很多涉及到生命周期的方法,比如:oncreate onresume onstop onNewIntent等,也有getParent,getWindow,getWindowManager等方法,还有menu,context menu的创建,dialog的创建,还有一些keyevent和dispatchevent等;还有这个runOnUiThread方法,看其源码,有点意思:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
暂时只看出了这么多,后续再补充。
还有在android.app这个包下,有Activity,ActivityGroup,ActivityManager,Application等类,如图所示: