Xamarin Android's activity detailed

Source: Internet
Author: User

Preface:

The previous article probably explained the process of creating a new Android. What we bring to you today is a detailed description of the activity, because in the development process we encountered

Several times the pits, embarrassed.

Life cycle

Same as in Java,

Pictures from the online ha, I can not draw.

1. Start activity: The system calls the OnCreate method first, then calls the OnStart method, and finally calls Onresume,activity into the running state.

2. Current activity is overwritten or locked by other activity: the system invokes the OnPause method, pausing the execution of the current activity.

3. The current activity is returned to the foreground or unlock screen by the overwritten state: The system calls the Onresume method and enters the running state again.

4. The current activity goes to the new activity interface or press the home key to return to the main screen, itself back to the background: the system will first call the OnPause method, and then call the OnStop method, into a stagnant state.

5. The user backs back to this activity: the system calls the Onrestart method first, then calls the OnStart method, and finally calls the Onresume method, again into the running state.

6. Current activity is in a covered state or the background is not visible, that is, the 2nd and 4th steps, the system is out of memory, kill the current activity, and then the user returned to the current activity: Call OnCreate method Again, OnStart method, Onresume method To enter a running state.

7. When exiting the current activity: The system calls the OnPause method first, then calls the OnStop method, and finally calls the Ondestory method to end the current activity.

The functions mentioned above can be rewritten in avtivity:

The newly created activity defaults to only the OnCreate function.

usingSystem;usingAndroid.app;usingandroid.content;usingAndroid.runtime;usingandroid.views;usingAndroid.widget;usingAndroid.os;usingAndroid.util;namespacefirstandroidapp{[Activity (Label="Firstandroidapp", Mainlauncher =true, Icon ="@drawable/icon")]     Public classmainactivity:activity {intCount =1; protected Override voidOnCreate (Bundle bundle) {Base.            OnCreate (bundle); //Set Our view from the "main" layout resourceSetcontentview (Resource.Layout.Main); //Get Our buttons from the layout resource,//And attach an event to itButton button = findviewbyid<button>(Resource.Id.MyButton); button. Click+=Delegate{button. Text =string. Format ("{0} clicks!", count++);        }; }        protected Override voidOnStart () {Log.debug ("OnStart","activity back to the front desk"); Base.        OnStart (); }        protected Override voidOnresume () {Log.debug ("Onresume","Onresume called"); Base.        Onresume (); }        protected Override voidOnStop () {Log.debug ("OnStop","OnStop called"); Base.        OnStop (); }        protected Override voidOnDestroy () {Log.debug ("ondestory","system is destroyed"); Base.        OnDestroy (); }        protected Override voidOnrestart () {Log.debug ("Onrestart","system back to the front desk"); Base.        Onrestart (); }    }}

There is also a life cycle that triggers activity, which is also entered when the screen is rotated. It also causes the current activity to occur ondestroy-> OnCreate, which reconstructs the current activity and interface layout. If the current activity has data loaded, it will cause a duplicate load.

Life cycle is good to understand, but if it is Android small white words, or oneself write down the code, hit the breakpoint on their own debugging, so as to facilitate their own understanding. Take a look at the life cycle, and then find out how the activity starts.

Activity four ways to start

Here the words quoted under the park Bo Friends of the article http://www.cnblogs.com/meizixiong/archive/2013/07/03/3170591.html I think the diagram is very clear.

First, the introduction of the starting mode

The startup mode is simply the activity startup policy, the Android:launchmode property setting of the tag in androidmanifest.xml; in Xamarin, add a attribute to each activity

After compiling, the corresponding configuration is generated in Androidmanifest.xml.

The starting mode has 4 kinds, namely standard, Singletop, Singletask, singleinstance;

Before explaining the starting mode, it is necessary to explain the concept of "task stack" first.

Task stack

Each application has a task stack, which is a stack of functions similar to that of a function call, and the order represents the order in which the activity appears; For example, Activity1-->activity2-->activity3, the task stack is:

Second, the starting mode

(1) Standard: Every time the activity is activated (startactivity), the activity instance is created and put into the task stack;

(2) Singletop: If an activity itself activates itself, that is, the task stack top is the activity, you do not need to create, the rest of the case to create activity instances;

(3) Singletask: If the activity to be activated in the task stack exists in the instance, you do not need to create, just need to put this activity into the top of the stack, and the activity of the activity above the instance of pop;

(4) SingleInstance: If Mainactivity instance is created in the task stack of application 1, if Application 2 also activates mainactivity, then no need to create, two apps to share the activity instance;

Application of Singtask:

can be used to exit the entire application.

Set the main activity to Singtask mode, then transfer the activity to the main activity in order to exit, then rewrite the onnewintent function of the main activity and add a finish to the function.

We can use the characteristics of Singtask to complete a number of small functions, such as ordinary people see the "Press again to quit the application", in fact, is the monitoring back key, in a short period of continuous click operation.

Create a new activity, named Secondactivity, the content is very simple

[Activity (Label ="secondactivity")]     Public classsecondactivity:activity {protected Override voidOnCreate (Bundle savedinstancestate) {Base.            OnCreate (savedinstancestate);            Setcontentview (Resource.Layout.Second); //Create your application here} DateTime? Lastbackkeydowntime;//record the last time the back was pressed         Public Override BOOLOnKeyDown ([Generatedenum] KeyCode keycode, keyevent e) {if(KeyCode = = Keycode.back && e.action = = Keyeventactions.down)//monitoring the back key            {                if(!lastbackkeydowntime.hasvalue | | Datetime.now-lastbackkeydowntime.value >NewTimeSpan (0,0,2) {Toast.maketext ( This,"Press once again to exit the program", Toastlength.short).                    Show (); Lastbackkeydowntime=DateTime.Now; }                Else{Intent Intent=NewIntent (); Intent. SetClass ( This,typeof(mainactivity));                StartActivity (Intent); }                return true; }            return Base.        OnKeyDown (KeyCode, E); }    }

Click button in mainactivity to jump to secondactivity

protected Override voidOnCreate (Bundle bundle) {Base.         OnCreate (bundle); //Set Our view from the "main" layout resourceSetcontentview (Resource.Layout.Main); //Get Our buttons from the layout resource,//And attach an event to itButton button = findviewbyid<button>(Resource.Id.MyButton); button. Click+=Delegate{Intent Intent=NewIntent ( This,typeof(secondactivity));          StartActivity (Intent); };} protected Override voidonnewintent (Intent Intent) {Finish ();}

Effect:

Here is a little bit of Singtask description:

Singletask If an instance of the activity is already in the stack, the instance is reused (Onnewintent () of the instance is invoked). When reused, the instance is returned to the top of the stack, so the instances above it will be removed from the stack. If the instance does not exist in the stack, a new instance is created to be put into the stack. in order to verify that the instance on Mainactivity is destroyed, we rewrite the ondestory function in secondavtivity to log:
 
 

From this, we can confirm that it was destroyed, hahaha.

Activity Transfer Value

Finally, in a little description of the activity value bar, open secondactivity in mainactivity, add the following code

New Intent (thistypeof(secondactivity)); Intent. PutExtra ("name","hushuai"); StartActivity (intent);

Then receive it in the OnCreate function of secondactivity:

Base . OnCreate (savedinstancestate); Setcontentview (Resource.Layout.Second); string name = Intent.getstringextra ("name"); Toast.maketext (this" who am I?") Of course I am "" !   ", Toastlength.short). Show ();

Finally, you will see the following:

This is the simplest way to find out more and to search for yourself. I have to write it before I know it.

At last

Just write here, after all, in the company or to work. Write something every night, come up early this morning the company added the last bit. Write carefully, afraid of being led to see.

The article writes a bit slow, the daytime work also is busy, at night oneself again makes some extra money, not easy ah.

And then put something I do now interface diagram Bar, after all, I am not art, I am a person to do, so a little ugly.

And then we will share some of the problems encountered, blogging speed is a bit slow, and then is the article typesetting headache.

Hope everyone support, 3Q.

Spit groove A bit, why Blog Park category no Xamarin series?

Xamarin Android's activity detailed

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.