android判断用户是否登录
直接上代码:(超详细)
1. 首先是AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tool="http://schemas.android.com/tools" package="com.example.express_delivery"> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" /> <!-- 访问网络,进行地图相关业务数据请求,包括地图数据,路线规划,POI检索等 --> <uses-permission android:name="android.permission.INTERNET" /> <!-- 获取网络状态,根据网络状态切换进行数据请求网络转换 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 读取外置存储。如果开发者使用了so动态加载功能并且把so文件放在了外置存储区域,则需要申请该权限,否则不需要 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- 写外置存储。如果开发者使用了离线地图,并且数据写在外置存储区域,则需要申请该权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 这个权限用于进行网络定位 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 这个权限用于访问GPS定位 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> <!-- 允许读取手机的状态 --> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <!-- 用于获取wifi的获取权限,wifi信息会用来进行网络定位 --> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <!-- 用于申请调用A-GPS模块 --> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <!-- 用于申请获取蓝牙信息进行室内定位 --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <application android:name=".DemoApplication" android:allowBackup="true" android:icon="@drawable/launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" tool:ignore="LockedOrientationActivity"> <activity android:name=".activity.SettingActivity"></activity> <activity android:name=".login_register.MyRegisterActivity" /> <activity android:name=".login_register.LoginActivity" /> <activity android:name=".NotLoginActivity" /> <activity android:name=".select_city.City_SelectActivity" /> <activity android:name=".FirstActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".RegisterActivity" /> <activity android:name=".SplashActivity" android:screenOrientation="portrait" /> <activity android:name=".Personal_PageActivity" /> <activity android:name=".bring.Delivery_help_bring" /> <activity android:name=".purchase.Delivery_help_purchase" /> <activity android:name=".ReverseGeoCodeDemo" /> <activity android:name=".GeoCoderDemo" /> <activity android:name=".TestActivity" /> <activity android:name=".SearchDemoActivity" /> <activity android:name=".MarkDemoActivity" /> <activity android:name=".SearchCityActivity" /> <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="weLEDW6SWoTAOXUzhA6QvQzl6Cbt3YY4" /> <meta-data android:name="com.amap.api.v2.apikey" android:value="d1c7a4f1729f99b28c5229503ed48560" /> <service android:name="com.amap.api.location.APSService" /> <activity android:name=".MainActivity"> <!-- <intent-filter> --> <!-- <action android:name="android.intent.action.MAIN" /> --> <!-- <category android:name="android.intent.category.LAUNCHER" /> --> <!-- </intent-filter> --> </activity> <activity android:name="com.mob.tools.MobUIShell" android:configChanges="keyboardHidden|orientation|screenSize" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:windowSoftInputMode="stateHidden|adjustResize" /> <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" /> </application> </manifest>
大家不用看那么多,有这么两个注意的:
(1)有一句 android:name=".DemoApplication"(我写了一个类,名为DemoApplication,继承的是Application)
<application android:name=".DemoApplication" android:allowBackup="true" android:icon="@drawable/launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:usesCleartextTraffic="true" tool:ignore="LockedOrientationActivity">
意思就是继承Application,来实现数据共享,大家可以参考这个
DemoApplication.java
package com.example.express_delivery; import android.app.Application; import com.baidu.mapapi.CoordType; import com.baidu.mapapi.SDKInitializer; import com.blankj.utilcode.util.Utils; import com.mob.MobSDK; public class DemoApplication extends Application { @Override public void onCreate() { super.onCreate(); //在使用SDK各组件之前初始化context信息,传入ApplicationContext SDKInitializer.initialize(this); //自4.3.0起,百度地图SDK所有接口均支持百度坐标和国测局坐标,用此方法设置您使用的坐标类型. //包括BD09LL和GCJ02两种坐标,默认是BD09LL坐标。 SDKInitializer.setCoordType(CoordType.BD09LL); MobSDK.init(this,"30640c6cc0e96", "195c8c7927621ee6651c0c2d3f5eb26d"); Utils.init(this); } }
(2)以及在其中一个activity下有这么个标签,<intent-filter>
<activity android:name=".FirstActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
代表他是第一启动项
FirstActivity.java
package com.example.express_delivery; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.Button; import com.example.express_delivery.login_register.MyRegisterActivity; import com.example.express_delivery.utils.UserUtils; public class FirstActivity extends AppCompatActivity { private Button btn_tomain; private Handler handler; private static final long DELAY = 2000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); //去掉标题栏 if (getSupportActionBar() != null){ getSupportActionBar().hide(); } final boolean isLogin= UserUtils.validateUserLogin(this); //等待2秒后自动跳转到 对应的Activity(相当于是闪屏页) handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (isLogin){ toMain(); }else { toLogin(); } } }, DELAY); } /** *跳转到主界面 * */ private void toLogin(){ Intent intent=new Intent(this,MyRegisterActivity.class); startActivity(intent); finish(); } private void toMain(){ Intent intent=new Intent(this,MainActivity.class); startActivity(intent); finish(); } }
2. 这里就不写是怎样注册的了,因为里边没有涉及到,我会再起一篇写注册登录的
LoginActivity.java
package com.example.express_delivery.login_register; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.express_delivery.MainActivity; import com.example.express_delivery.Personal_PageActivity; import com.example.express_delivery.R; import com.example.express_delivery.utils.UserUtils; import java.util.ArrayList; public class LoginActivity extends AppCompatActivity implements View.OnClickListener{ private TextView tv_register,tv_login_forget_psw; private DBOpenHelper mDBOpenHelper; private EditText et_login_phone,et_login_password; private Button btn_login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (getSupportActionBar() != null){ getSupportActionBar().hide(); } initView(); mDBOpenHelper = new DBOpenHelper(this); onclick(); btn_login.setOnClickListener(this); } private void initView() { tv_register = findViewById(R.id.tv_register); btn_login = findViewById(R.id.btn_login); et_login_phone = findViewById(R.id.et_login_phone); et_login_password = findViewById(R.id.et_login_password); tv_login_forget_psw = findViewById(R.id.tv_login_forget_psw); } private void onclick() { tv_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LoginActivity.this, MyRegisterActivity.class); startActivity(intent); finish(); } }); } public void onClick(View view){ switch (view.getId()) { case R.id.btn_login: String name = et_login_phone.getText().toString().trim(); String password = et_login_password.getText().toString().trim(); if (!UserUtils.vaLidateLogin(this, name)) { return; } if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password)) { ArrayList<User> data = mDBOpenHelper.getAllData(); boolean match = false; for (int i = 0; i < data.size(); i++) { User user = data.get(i); if (name.equals(user.getPhone()) && password.equals(user.getPassword())) { match = true; break; } else { match = false; } } if (match) { Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish();//销毁此Activity } else { Toast.makeText(this, "用户名或密码不正确,请重新输入", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "请输入你的用户名或密码", Toast.LENGTH_SHORT).show(); } break; } } }
其中大家注意到这几行的判断代码,(其余的是数据库的校验)
String name = et_login_phone.getText().toString().trim(); String password = et_login_password.getText().toString().trim(); if (!UserUtils.vaLidateLogin(this, name)) { return; }
UserUtils.java
package com.example.express_delivery.utils; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.text.TextUtils; import android.widget.Toast; import com.example.express_delivery.login_register.LoginActivity; import com.example.express_delivery.login_register.UserHelper; public class UserUtils { public static boolean vaLidateLogin(Context context, String phone) { /** * 判断用户当前手机号是否已经被注册 * 用户输入的手机号和密码是否匹配 */ //保存用户登录标记 boolean isSave = saveUser(context,phone); if (!isSave){ Toast.makeText(context, "系统错误,请稍后重试", Toast.LENGTH_SHORT).show(); return false; } //保存用户登录标记,在全局单类例之中 UserHelper.getInstance().setPhone(phone); return true; } public static boolean saveUser (Context context, String phone) { SharedPreferences sp = context.getSharedPreferences(SPConstants.SP_NAME_USER, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString(SPConstants.SP_KEY_PHONE, phone); boolean result = editor.commit(); return result; } public static boolean validateUserLogin(Context context){ return isLoginUser(context); } /** * 验证是否存在已登录用户 */ public static boolean isLoginUser (Context context) { boolean result = false; SharedPreferences sp = context.getSharedPreferences(SPConstants.SP_NAME_USER, Context.MODE_PRIVATE); String phone = sp.getString(SPConstants.SP_KEY_PHONE, ""); if (!TextUtils.isEmpty(phone)) { result = true; UserHelper.getInstance().setPhone(phone); } return result; } public static void logout (Context context) { // 删除sp保存的用户标记 boolean isRemove = removeUser(context); if (!isRemove) { Toast.makeText(context, "系统错误,请稍后重试", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(context, LoginActivity.class); // 添加intent标志符,清理task栈,并且新生成一个task栈 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } /** * 删除用户标记 */ public static boolean removeUser (Context context) { SharedPreferences sp = context.getSharedPreferences(SPConstants.SP_NAME_USER, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(SPConstants.SP_KEY_PHONE); boolean result = editor.commit(); return result; } }
SPConstants.java
package com.example.express_delivery.utils; public class SPConstants { public static final String SP_NAME_USER = "user"; public static final String SP_KEY_PHONE = "phone"; }
UserHelper.java
package com.example.express_delivery.login_register; /** * 1、用户登录 * 1、当用户登录时,利用SharedPreferences 保存登录用户的用户标记(手机号码) * 2、利用全局单例类UserHelper保存登录用户信息 * 1、用户登录之后 * 2、用户打开应用程序,检测SharedPreferences中是否存在登录用户标记 * ,如果存在则为UserHelp进行赋值,并且进入主页。如果不存在,则进入登录页面 * 2、用户退出 * 1、删除掉SharedPreferences保存的用户标记,退出到登录页面。 */ public class UserHelper { private static UserHelper instance; private UserHelper () {}; public static UserHelper getInstance() { if (instance == null) { synchronized (UserHelper.class) { if (instance == null) { instance = new UserHelper(); } } } return instance; } private String phone; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
到这里代码就放完了,如果有缺,大家可以留言评论,我会及时看到回复的(xml的布局文件没有放,我在注册登录篇会放)