获取全局上下文(getApplicationContext)_创建Shared Preference工具类_实现自动登录
===========================获取全局上下文(getApplicationContext)========================
1.在com.example.autologin.myapplication包中创建Myapplication extends Application
代码:
1 public class Myapplication extends Application 2 { 3 private static Context context; 4 5 @Override 6 public void onCreate() 7 { 8 super.onCreate(); 9 10 context = getApplicationContext(); 11 } 12 13 public static Context getAppContext() 14 { 15 return context; 16 } 17 }
2.在AndroidManifest.xml中添加属性, 申明Myapplication:
android:name="com.example.autologin.myapplication.Myapplication"
代码:
1 <!-- 申明Myapplication --> 2 <application 3 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 <!-- ....... --> 10 11 </application>
================================创建Shared Preference工具类==============================
在包com.example.autologin.utils中创建SpUtil.java类:
代码:
1 public class SpUtil 2 { 3 // 4 //通过全局上下文创建静态SharedPreferences对象 5 // 6 private static SharedPreferences sp = 7 Myapplication.getAppContext().getSharedPreferences("user",Context.MODE_PRIVATE); 8 9 //静态保存用户账号密码方法 10 public static void saveUser(String name, String pwd) 11 { 12 Editor edit = sp.edit(); 13 edit.putString("username", name); 14 edit.putString("pwd", pwd); 15 16 edit.commit(); 17 18 } 19 20 // 21 //保存是否有过登录的状态 22 // 23 public static void isLogin(boolean isLogin) 24 { 25 Editor edit = sp.edit(); 26 edit.putBoolean("islogin", isLogin); 27 edit.commit(); 28 } 29 30 // 31 //读取是否有过登录的状态 32 // 33 public static boolean getIsLogin() 34 { 35 return sp.getBoolean("islogin", false); 36 } 37 }
=============================实现自动登录============================
创建欢迎页面SplashActivity.java,读取登录状态,若有过登录则直接跳转主页面,没有登录过跳转登录页面
代码:
1 Handler handler = new Handler(); 2 handler.postDelayed(new Runnable() 3 { 4 @Override 5 public void run() 6 { 7 // 8 //如果有过登录 9 //直接跳转主页面 10 // 11 if (SpUtil.getIsLogin()) 12 { 13 Intent intent = new Intent(SplashActivity.this, MainActivity.class); 14 startActivity(intent); 15 SplashActivity.this.finish(); 16 } else 17 { 18 // 19 //如果没有登录过登录 20 //跳转登录页面 21 // 22 Intent intent = new Intent(SplashActivity.this, LoginActivity.class); 23 startActivity(intent); 24 SplashActivity.this.finish(); 25 } 26 27 } 28 }, 3000);
**注意: 将SplashActivity.java设置为启动页面