Detailed explanation of the instance of Android Application accessing public data
When the Android system runs every program application, it will create an Application object to store public variables related to the entire application.
An Android application will only generate an Application object. The Application object obtained in different activities is the same, so the Application object is a singleton (SingleTon).
Application objects are very suitable for storing some data related to the entire application, such as application version, application login account, data cache, etc.
Use Application objects to store public data or data delivery
In Android development, the switching of activity is very frequent, which can be almost the same as the switching between different web pages in a website. Then different activities need to store public information (such as only one currently logged in user) and data transmission. The following is a method to use Application objects to store logged-in user information. You can find that this is very convenient for different activities to obtain logged-in user information.
public class MyApplication extends Application { public String appVersion = "v1.0"; //Current login user private User loginUser = new User(); public User getLoginUser(){ return loginUser; } public void userLogin(User user){ (()); (()); } public void userLogout(){ loginUser = new User(); } }
public class MainActivity extends Activity { private MyApplication mApplication; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); // Get the Application object of the entire application // The object obtained in different activities is the same mApplication = (MyApplication) getApplication(); } /** * Generally, only login user information is set in the login interface, and in other activities * You can get logged in user information through the Application object */ private void login(){ User user = new User(); (1); ("Raysmond"); // Save login user information into the Application object (user); } }
It can be found that through Application objects, data sharing can be easily achieved between different activities. This is much more convenient than passing data through Bundle every time you switch activities.
The above are the development articles using Android Application. There are many articles about Android development in this website. I hope you can search and refer to it. Thank you for reading. I hope it can help you. Thank you for your support for this website!