Application Class
In Android, launch an app that first initializes the application and then checks the androidmanifest.xml manifest file with it to select the activity that needs to start first.
In activity, you can use the Getapplication () method to get an instance of the application, use it to get the theme of the current application, the contents of the resource file, and so on, and we can add our own global properties, such as user. For example, to develop a game that requires saving fractions, then we can inherit application.
First, write a application subclass:
Import Android.app.application;public class Gameapplication extends application { private int score; public int Getscore () { return score; } public void SetScore (int score) { this.score = score; }}
And then Change it in the Manifest.xml file.
<application android:name= ". Gameapplication "android:icon=" @drawable/icon "android:label=" @string/app_name "> <activity android:name =". Demoactivity " android:label=" @string/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> < /intent-filter> </activity> <activity android:name= "Resultactivity" ></activity> </application>
Noted the addition of android:name= ". Gameapplication ".
after the change, look down :
public class Demoactivity extends Activity {public button button; @Override public void OnCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.main); button= (Button) Findviewbyid (R.id.button); ((gameapplication) getapplication ()). SetScore (+); Button.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {Intent intent=new Intent (); Intent.setclass (Demoactivity.this, Resultactivity.class); startactivity (intent);}});} }
By setting a score in this activity, we can take it out of other activity:
public class Resultactivity extends Activity { @Override protected void onCreate (Bundle savedinstancestate) { c2/>//TODO auto-generated Method Stub super.oncreate (Savedinstancestate); Setcontentview (r.layout.other); TextView tv= (TextView) Findviewbyid (r.id.tv); int score= ((gameapplication) Getapplicationcontext ()). Getscore (); Tv.settext ("Your score is:" +score);} }
This is just a simple example, of course, want to complete the above functions, the use of intent value can be, this also seems troublesome, but, assuming that there is a lot of activity, the use of such a method will find very practical, is not using Sharepreference can also complete similar function, can, however, efficiency is much worse than this, sharepreference is mainly used to store data, You can exit the program by saving the simple data you need to save into sharepreference, of course, complex data, but also use Sqllite.
Inherit application for Android data sharing