Android Global get Context with using Intent to pass objects

Source: Internet
Author: User

===================== Global Get Context========================

Many areas of Android development need to use Context, such as pop-up Toast, launch activities, send broadcasts, operate the database ...

Because many operations are performed in an activity and the activity itself is a context object, getting the context is not so difficult.

However, when the architecture of the application begins to become more complex, many of the logic code will be out of the Activity class, which in some cases is not so easy to get the context.

Android provides a application class that automatically initializes the class whenever the application starts . And we can customize a application class to manage some of the global state information in the program, such as the global context.

 public  class  myapplication extends   application { private  Span style= "color: #0000ff;"    >static   context context; @Override  public  void   OnCreate () { super  .oncreate ();    Context  =getapplicationcontext ();  public  static   context GetContext () { return   context; }}

Here we rewrite the OnCreate () method of the parent class and get an application-level Context by calling the Getapplicationcontext () method, and then provide a static GetContext () method, where you will just get the Context to return.

Next, you need to tell the system, when the program starts should initialize the MyApplication class, the Androidmanifest file under the <application> tag to be specified on it.

<android:name= "MyApplication">  ...  </ Application >

In this way, a global access to the context mechanism has been implemented, and then no matter where you want to use the context anywhere in the project, you just need to call Myapplication.getcontext ().

Toast.maketext (Myapplication.getcontext (), "Global context gets successful", Toast.length_short). Show ();

===================== using Intent to pass objects =======================

There are usually two implementations of using Intent to pass objects, Serializable and parcelable.

Serializable way:

Serializable is the meaning of serialization, which indicates that an object is converted to a state that can be stored or transportable. The serialized object can be transferred on the network or stored locally. As for the serialization method is also very simple, only need to let a class to implement serizable this interface can be.

 Public classFestivalImplementsSerializable {PrivateString name; PrivateString data;  PublicFestival (String name,string data) { This. Name =name;  This. data =data; }     PublicString GetName () {returnname; }     PublicString GetData () {returndata; }}

This allows the Festival class to implement the Serializable interface so that all Festival objects can be serialized.

        New Festival ("New Year's Day", "January 1");         New Intent (firstactivity.  this, secondactivity. class );        Intent.putextra ("Festival_object", festival);        StartActivity (intent);

Here we create an instance of Festival and pass it directly into the PutExtra () method, passing the object through StartActivity ().

        Festival Festival = (Festival) getintent (). Getserializableextra ("Festival_object");

This invokes the Getserializableextra () method to get the serialized object passed over, then transforms it down into a Festival object, which successfully implements the function of passing objects using Intent.

Parcelable Way:

The implementation principle of the Parcelable method is to decompose a complete object, and each part of the decomposition is a data type supported by Intent, which also implements the function of passing objects.

 Public classPersonImplementsparcelable {PrivateString name; Private intAge ; //omitting set and get methods    protectedPerson (Parcel in) {name= In.readstring ();//Read nameAge = In.readint ();//Read Age    }     Public Static FinalCreator<person> Creator =NewCreator<person>() {@Override PublicPerson Createfromparcel (Parcel in) {return NewPerson (in); } @Override PublicPerson[] NewArray (intsize) {            return NewPerson[size];    }    }; @Override Public intdescribecontents () {return0; } @Override Public voidWritetoparcel (Parcel dest,intflags) {dest.writestring (name);//Write nameDest.writeint (age);//Write Age    }}

First let the person class implement the Parcelable interface, so that the two methods of Describecontents () and Writetoparcel () must be rewritten. where the Describecontents () method returns 0 directly, and the Writetoparcel () method needs to call Parcel's WriteXxx () method to write out field one by one in the person class.

In addition to this, you must provide a constant named CREATOR in the person class, where an implementation of the Parcelable.creator interface is created and the generic is specified as man.

Next you need to rewrite the two methods of Createfromparcel () and NewArray () in the Createfromparcel () method to read the name and age fields just written out and create a person object to return, where name and AG E is read by the Readxxx () method that calls Parcel, and note that the reading order here must be exactly the same as the write order. The NewArray () method only needs a new person array and uses the size passed in the method as an array.

        Person person = (person) getintent (). Getparcelableextra ("Person_object");

You can still use the same code to pass the person object, except that the Getparcelableextra () method is called when the object is fetched, and the other places are exactly the same.

The Serializable and Parcelable methods are both feasible when passing objects, and comparing Serializable is simpler, but because the whole object is serialized, the efficiency will be lower than the parcelable way. These two methods should be used rationally according to the situation.

Android Global get Context with using Intent to pass objects

Related Article

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.