Android Activity startup process analysis (source code 4.4)

Source: Internet
Author: User
Tags mremote

To tell the truth, Android source code changes from 2.3 to 4.4 is pretty much, especially the media section, although the overall framework is not much change, but looking for code to see it is quite troublesome. The most wounded in Android is the use of java,jni,jvm,nativity C + +, and so on, a variety of design patterns rampant, of course, in the course of learning the source of the programming language is also aware of the importance of the foundation, data structure, design patterns.

Android Source Code Classic Place:

1. Extensive use of various design modes such as single-case mode, decoration mode, Engineering Factory mode, adapter mode and so on.

2. The IPC communication is carried out using the binder driver.

3. Redesigned the message processing mechanism.

4. Added strength pointer management.

5. Design the rights management of activity security.

6. Make a significant contribution to the application developer's scalability and maintenance.

7. The use of JNI technology.

8. Optimized power Management Services.

。。。。。 Wait a minute

Of course, there are also shortcomings in the place.

1. Android boot slow.

Because the use of JNI,JVM causes the need to load many classes and class libraries, and the start of various services. For the user experience, Sureface is used.

After starting the above start launcher, scanning each application information and so on.

2. Android is developed for embedded products. In fact, the memory use effect is not ideal, prone to fragmentation, resulting in the use of Android more and more slowly.

3. Less theme customization, lack of large-scale games.

4. App resident memory causes no long standby time.

Well, don't complain so much, life is helpless enough. Let's start with the analysis.

1. In an Android system, the application is composed of activity, so the application's startup process is actually the startup process of the default activity in the application. That is, when the Desktop Program (launcher) starts, scanning the individual app information, clicking on the application icon in the device screen will cause the default activity in the Android app to start up, thus launching the application. The feature of this startup is that a new process is initiated to load the corresponding activity.

2. From the above: The default startup activity is initiated by the launcher (OnClick method), in fact, is to parse androidmanifest.xml in the activity tag and <Intent-filter > tags. The activity is then started by the Startactivitysafely method.

1 Launcher.java (E:\baiduyundownload\intel_x86_sysimg_4.4_source_files_20131206\intel_x86_sysimg_4.4_source_ FILES_20131206\PACKAGES\APPS\LAUNCHER2\SRC\COM\ANDROID\LAUNCHER2)2 3      Public voidOnClick (View v) {4         //Make sure this rogue clicks Don ' t get through while AllApps are launching, or after the5         //View has detached (it's possible for this and happen if the view is removed mid touch).6         if(V.getwindowtoken () = =NULL) {7             return;8         }9 Ten         if(!mworkspace.isfinishedswitchingstate ()) { One             return; A         } -  -Object tag =V.gettag (); the         if(Tag instanceof shortcutinfo) { -             //Open Shortcut -Final Intent Intent =((shortcutinfo) tag). Intent; -             int[] pos =New int[2]; + V.getlocationonscreen (POS); -Intent.setsourcebounds (NewRect (pos[0], pos[1], +pos[0] + v.getwidth (), pos[1] +v.getheight ())); A  atBoolean success = startactivitysafely(V, intent, tag); -  -             if(Success &&v instanceof Bubbletextview) { -Mwaitingforresume =(Bubbletextview) v; -Mwaitingforresume.setstaypressed (true); -             } in}Else if(Tag instanceof folderinfo) { -             if(v instanceof foldericon) { toFoldericon fi =(Foldericon) v; + Handlefolderclick (FI); -             } the}Else if(v = =Mallappsbutton) { *             if(Isallappsvisible ()) { $Showworkspace (true);Panax Notoginseng}Else { - Onclickallappsbutton (v); the             } +         } A}
boolean startactivitysafely(View V, Intent Intent, Object tag) {Boolean Success=false; Try{Success= startactivity(V, intent, tag); } Catch(activitynotfoundexception e) {Toast.maketext ( ThisR.string. Activity_not_found, Toast.length_short). Show (); LOG.E (TAG,"unable to launch. tag="+ Tag +"intent="+Intent, E); }        returnsuccess; }
Booleanstartactivity(View V, Intent Intent, Object tag)        {intent.addflags (intent.flag_activity_new_task);  try {//Only launch using the new animation if the shortcut have not opted out (this is a/private            Contract between launcher and May is ignored in the future). Boolean uselaunchanimation = (v! = null) &&!intent.hasextra (Intent_extra_ignore_launch_animati ON);
Uselaunchanimation indicates whether to use a click on the Launcher Desktop icon, will be the icon to enlarge the animation before entering the application, before 2.3 is not this option. if (uselaunchanimation) {Activityoptions opts = activityoptions.makescaleupanimation (V, 0, 0, V.getmeasuredwidth (), V.getmeasuredheight ());startactivity(Intent, Opts.tobundle ()); } else {startactivity(intent); } return true; } catch (SecurityException e) {Toast.maketext (this, R.string.activity_not_found, Toast.length_short). Show (); LOG.E (TAG, "Launcher does not" has the permission to launch "+ Intent +". Make sure to create a MAIN intent-filter for the corresponding activity "+" or use the exported attrib Ute for this activity. "+" + "tag=" + tag + "intent=" + intent, E); } return false; }

Above the

StartActivity (Intent, Opts.tobundle ()); no definition found in Launcher.java, actually defined in Launcher's base class, and need to go to Activity.java to find the definition.

Activity.java (Base\core\java\android\app)

@Override Public void startactivity(Intent Intent, Bundle options) {if(Options! =NULL) {
The second parameter passed in-1 means that the return result after this actvity end is not required. Startactivityforresult (Intent,-1, Options); } Else { //Note We want to go through this call is compatibility with//Applications that could have overridden the method.Startactivityforresult (Intent,-1); } }
 Public void Startactivityforresult(Intent Intent,intRequestcode, Bundle options) {        if(Mparent = =NULL) {
The mparent here is definitely null, because it's starting from launcher and there's definitely no parent activity.
The minstrumentation here is a member variable of the activity class, and its type is intrumentation, defined in frameworks/base/core/java/android/app/ In the Instrumentation.java file, it is used to monitor the interaction of applications and systems.
The Mmainthread is also a member variable of the activity class, and its type is Activitythread, which represents the main thread of the application, Here you get the Applicationthread member variable inside it by Mmainthread.getapplicationthread, it's a binder object, and we'll see that Activitymanagerservice will use it to work with the activity Thread to communicate between processes. What we should note here is that the mmainthread here represents the process that the launcher application runs.
The Mtoken is also a member variable of the activity class, which is the remote interface of a binder object.
Instrumentation.activityresult ar=minstrumentation. execstartactivity ( This, Mmainthread.getapplicationthread (), Mtoken, This, Intent, requestcode, options); if(AR! =NULL) {Mmainthread.sendactivityresult (Mtoken, Membeddedid, Requestcode, Ar.getresultco De (), ar.getresultdata ()); } .......}

Instrumentation.java (Base\core\java\android\app) Publicactivityresult execstartactivity(Context who, IBinder Contextthread, IBinder token, Activity tar Get, Intent Intent,intRequestcode, Bundle options) {Iapplicationthread Whothread=(Iapplicationthread) Contextthread; if(Mactivitymonitors! =NULL) {synchronized (Msync) {finalintN =mactivitymonitors.size ();  for(intI=0; i<n; i++) {Final activitymonitor am= Mactivitymonitors.Get(i); if(Am.match (WHO,NULL, Intent)) {Am.mhits++; if(Am.isblocking ()) {returnRequestcode >=0? Am.getresult ():NULL; }                         Break; }                }            }        }        Try{intent.migrateextrastreamtoclipdata (); Intent.preparetoleaveprocess ();
The activitymanagernative.getdefault here returns to Activitymanagerservice's remote interface, the Activitymanagerproxy interface, and you'll know It (Iactivitymanager) 。
intent.resolvetypeifneeded returns the MIME type of this intent, which generally does not androidmanifest.xml set the MIME type of the mainactivity, and therefore returns null here.
intresult = Activitymanagernative.getdefault (). StartActivity(Whothread, Who.getbasepackagename (), intent , intent.resolvetypeifneeded (Who.getcontentresolver ()), token, target!=NULL? Target.membeddedid:NULL, Requestcode,0,NULL,NULL, Options); Checkstartactivityresult (result, intent); } Catch(RemoteException e) {}return NULL; }
Activitymanagernative.java (Base\core\java\android\app) Public int startactivity(iapplicationthread caller, String callingpackage, Intent Intent, String Resolvedtyp E, IBinder Resultto, String resultwho,intRequestcode,intStartflags, String profilefile, Parcelfiledescriptor profilefd, Bundle options) throws RemoteException {
It's already very close to the core, 1. Constructs the parcel data packet and the reply package, and then hits the relevant intent to start, and then delivers it to the server (transact) Par via the Activitymanagerservice method of the remote object Mremote (Binder IPC) CEL Data=Parcel.obtain (); Parcel reply=Parcel.obtain (); Data.writeinterfacetoken (Iactivitymanager.descriptor); Data.writestrongbinder (Caller!=NULL? Caller.asbinder ():NULL); Data.writestring (Callingpackage); Intent.writetoparcel (data,0); Data.writestring (Resolvedtype); Data.writestrongbinder (Resultto); Data.writestring (resultwho); Data.writeint (Requestcode); Data.writeint (Startflags); Data.writestring (Profilefile); if(PROFILEFD! =NULL) {Data.writeint (1); Profilefd.writetoparcel (data, parcelable.parcelable_write_return_value); } Else{data.writeint (0); } if(Options! =NULL) {Data.writeint (1); Options.writetoparcel (data,0); } Else{data.writeint (0); } mremote.transact (start_activity_transaction, data, reply,0); Reply.readexception (); intresult =Reply.readint (); Reply.recycle (); Data.recycle (); returnresult; }

Android Activity startup process analysis (source code 4.4)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.