Get Global Context (Getapplicationcontext) _ Create shared Preference Tool Class _ Implement automatic login
=========================== Gets the global context (Getapplicationcontext) ========================
1. Create the MyApplication extends in the Com.example.autologin.myapplication package application
Code:
1 Public classMyApplicationextendsApplication2 {3 Private Staticcontext context;4 5 @Override6 Public voidonCreate ()7 {8 Super. OnCreate ();9 TenContext =Getapplicationcontext (); One } A - Public StaticContext getappcontext () - { the returncontext; - } -}
2. Add an attribute in Androidmanifest.xml, stating MyApplication:
Android:name= "Com.example.autologin.myapplication.Myapplication"
Code:
1 <!--Disclaimer MyApplication -2 <Application3 Android:name= "Com.example.autologin.myapplication.Myapplication"4 Android:allowbackup= "true"5 Android:icon= "@drawable/ic_launcher"6 Android:label= "@string/app_name"7 Android:theme= "@style/apptheme" >8 9 <!-- ....... -Ten One </Application>
================================ Creating a shared preference tool class ==============================
Create the Sputil.java class in package Com.example.autologin.utils:
Code:
1 Public classSputil2 {3 //4 //Create a static Sharedpreferences object from a global context5 //6 Private StaticSharedpreferences SP =7Myapplication.getappcontext (). Getsharedpreferences ("User", context.mode_private);8 9 //static Save user account password methodTen Public Static voidSaveuser (string name, string pwd) One { AEditor edit =Sp.edit (); -Edit.putstring ("username", name); -Edit.putstring ("pwd", PWD); the - edit.commit (); - - } + - // + //Save if you have a status of logged in A // at Public Static voidIsLogin (Booleanislogin) - { -Editor edit =Sp.edit (); -Edit.putboolean ("IsLogin", islogin); - edit.commit (); - } in - // to //Read if there is a status of logged in + // - Public Static BooleanGetislogin () the { * returnSp.getboolean ("IsLogin",false); $ }Panax Notoginseng}
============================= Implement automatic Login ============================
Create Welcome page Splashactivity.java, read the login status, if you have logged in directly to the main page, did not log on to the jump login page
Code:
1Handler Handler =NewHandler ();2Handler.postdelayed (NewRunnable ()3 {4 @Override5 Public voidRun ()6 {7 //8 //If you have ever logged in9 //jump directly to the main pageTen // One if(Sputil.getislogin ()) A { -Intent Intent =NewIntent (splashactivity. This, Mainactivity.class); - startactivity (intent); theSplashactivity. This. Finish (); -}Else - { - // + //If you have not logged in - //Jump Login Page + // AIntent Intent =NewIntent (splashactivity. This, Loginactivity.class); at startactivity (intent); -Splashactivity. This. Finish (); - } - - } -}, 3000);
* * Note: Set Splashactivity.java as the startup page
Get Global Context (Getapplicationcontext) _ Create shared Preference Tool Class _ Implement automatic login