Use Application to access public data, such as login information...
When running each Application, the Android system creates an Application object to store public variables related to the entire Application.
An Android Application generates only one Application object. The Application object obtained in different activities is the same, so the Application object is a SingleTon ).
Application objects are suitable for storing data related to the entire Application, such as the Application version, Application Logon account, and data cache.
Use Application object to store public data or data transmission
In android development, activity switching is very frequent and can be similar to switching between different webpages on a website. Therefore, different activities need to store public information (such as only one currently logged-on user) and data transmission. The following is a method for storing Login User information using the Application object. It can be found that different activities can easily obtain login user information.
Public class MyApplication extends Application {public String appVersion = "v1.0"; // The current logon User private User loginUser = new User (); public User getLoginUser () {return loginUser ;} public void userLogin (User user) {loginUser. setUserId (user. getUserId (); loginUser. setUserName (user. getUserName ();} public void userLogout () {loginUser = new User ();}}
Public class MainActivity extends Activity {private MyApplication mApplication; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the Application object of the entire Application // The object obtained in different activities is the same mApplication = (MyApplication) getApplication ();} /*** Generally, only logon user information is set on the logon interface. In other activities, * You can obtain logon user information through the Application Object */private void login () {User user = new User (); user. setUserId (1); user. setUserName ("Raysmond"); // Save the login user information to mApplication in the Application object. userLogin (user );}}
It can be found that data can be easily shared between different activities through the Application object. This is more convenient than passing data through Bundle during every activity switchover.