美文网首页资料
Android开发-注册登录与手机验证登录

Android开发-注册登录与手机验证登录

作者: Syydnrycx丶 | 来源:发表于2018-11-27 08:36 被阅读440次

效果图

登陆与注册 下拉列表 手机验证码

前言

  • 这篇主要讲如何通过数据库添加用户注册账户并且验证账户并且登录,还可以通过手机接收验证码登录。

准备

  • 登陆 MOB官网 注册账户,注册好后登录,进入后台,并且我们添加一个应用。
  • 应用名称根据个人喜好。这里我随便命名了个11应用,这里我们进入概况。


  • 这里我们记录一下应用Appkey与App Secret,后面我们会用到,并且我们开启短信验证功能。


  • 弄完后,我们回到 MOB官网 进入下载中心。
  • 然后我们下载短信验证功能的包。


  • 我是通过离线下载的SDK包,然后解压出我们需要的东西[路径(sms/SMSSDK/SMSSDK/libs)]然后解压这4个jar包。


  • 到这里,要准备的东西基本全了,有漏的后面再补充。

建立工程

  • 这里我就不多说了,新建一个标准的工程,然后开始添加我们需要的东西。并且将我们解压的4个jar包加进工程里。


开始

准备布局

  • 我们先把需要的布局准备好,actuvuty_main.xml我只放了个登录成功的显示。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登陆成功"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
  • 登录界面布局文件logic_layout.xml十分简单,放置了几个Button与编辑框,编辑框下拉我用的是ListPopupWindow来显示。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_marginTop="50dp"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="账户:" />

        <com.example.syydnrycx.sqlitelogin.Class.ClearEditText
            android:id="@+id/user_name"
            android:layout_width="220dp"
            android:layout_height="40dp"
            android:drawableLeft="@drawable/user_name"
            android:drawablePadding="6dp"
            android:hint="name_tip"
            android:singleLine="true"
            android:background="@drawable/myedit_style" >
            <requestFocus />
        </com.example.syydnrycx.sqlitelogin.Class.ClearEditText>

        <ImageButton
            android:id="@+id/user_btn_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/lg_down"
            android:paddingRight="2dip"
            android:scaleType="fitXY" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="密码:" />

        <EditText
            android:id="@+id/user_pass"
            android:layout_width="220dp"
            android:layout_height="40dp"
            android:background="@drawable/myedit_style"
            android:layout_marginLeft="5dp"
            android:hint="密码" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="手机:" />

        <EditText
            android:id="@+id/ed_phone"
            android:layout_width="220dp"
            android:layout_height="40dp"
            android:layout_marginLeft="5dp"
            android:background="@drawable/myedit_style"
            android:hint="手机号" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="验证码:" />

        <EditText
            android:id="@+id/ed_code"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:background="@drawable/myedit_style"
            android:layout_marginLeft="5dp"
            android:hint="验证码" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/bt_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="80dp"
            android:background="@drawable/mybutton_style"
            android:text="登录" />

        <Button
            android:id="@+id/bt_register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:background="@drawable/mybutton_style"
            android:text="注册" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/bt_getphonecore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="60dp"
            android:background="@drawable/mybutton_style"
            android:text="获取验证码" />
        <Button
            android:id="@+id/bt_corelogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:background="@drawable/mybutton_style"
            android:text="验证码登录" />
    </LinearLayout>


</LinearLayout>
  • 注册界面布局文件register_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:layout_marginTop="20dp"
        android:orientation="horizontal" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="帐号:" />
        <EditText
            android:id="@+id/usernameRegister"
            android:layout_width="220dp"
            android:layout_height="40dp"
            android:background="@drawable/myedit_style"
            android:layout_marginLeft="5dp" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="密码:" />

        <EditText
            android:id="@+id/passwordRegister"
            android:layout_width="220dp"
            android:layout_height="40dp"
            android:background="@drawable/myedit_style"
            android:layout_marginLeft="5dp" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/Register"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/mybutton_style"
            android:text="注册" />
    </LinearLayout>

</LinearLayout>

java

  • java文件我会挑些重要的解释,剩余我觉得无关紧要的,大家可以在我的Github上下载下来看。

  • 数据库建立 DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
    static String name="user.db";
    static int dbVersion=1;
    public DatabaseHelper(Context context) {
        super(context, name, null, dbVersion);
    }
    //只在创建的时候用一次
    public void onCreate(SQLiteDatabase db) {
        String sql="create table user(id integer primary key autoincrement,username varchar(80),password varchar(80))";
        db.execSQL(sql);
    }
    //升级
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}
  • 登录、注册、获取ListPopupWindow显示账户 UserService.java
public class UserService {
    private ArrayList<String> usernameList = new ArrayList<>();
    private DatabaseHelper dbHelper;
    private String s = null;

    public UserService(Context context){
        dbHelper=new DatabaseHelper(context);
    }

    //登录用
    public boolean login(String username,String password){
        SQLiteDatabase sdb=dbHelper.getReadableDatabase();
        String sql="select * from user where username=? and password=?";
        Cursor cursor=sdb.rawQuery(sql, new String[]{username,password});
        if(cursor.moveToFirst()==true){
            cursor.close();
            return true;
        }
        return false;
    }

    //注册用
    public boolean register(User user){
        //用getReadable和getWriteable都可以创建或者打开一个数据库并返回一个可对数据库进行读写操作的对象,当数据库满R可以只读,W会报错
        SQLiteDatabase sdb=dbHelper.getReadableDatabase();
        String sql="insert into user(username,password) values(?,?)";
        Object obj[]={user.getUsername(),user.getPassword()};
        sdb.execSQL(sql, obj);
        return true;
    }

    public ArrayList<String> getAll() {
        SQLiteDatabase sdb=dbHelper.getReadableDatabase();
        //查询获得游标
        Cursor cursor = sdb.query ("user",null,null,null,null,null,null);
        //判断游标是否为空
        if(cursor.moveToFirst()) {
            //遍历游标
            do{
                //获得用户名
                usernameList.add(cursor.getString(1));
            }while(cursor.moveToNext());
            cursor.close();
        }
        return usernameList;
    }
}
  • 主要的登录逻辑与手机验证获取
public class LoginActivity extends Activity implements View.OnClickListener{

    private ArrayList<String> usernamelList;

    private Button bt_login,bt_register,bt_getphonecore,bt_corelogin;
    private ImageButton image_btn;
    private EditText edit_username;
    private EditText edit_password;
    private EditText edit_phone;
    private EditText edit_cord;

    private UserService uService = null;
    private ListPopupWindow listPopupWindow;
    private String phone_number;
    private String cord_number;
    EventHandler eventHandler;
    private boolean coreflag=true;

    private Context context;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.logic_layout);

        initViews();
        sms_verification();

    }

    private void initViews() {

        bt_login=(Button) findViewById(R.id.bt_login);
        bt_register=(Button) findViewById(R.id.bt_register);
        bt_getphonecore=(Button) findViewById(R.id.bt_getphonecore);
        bt_corelogin=(Button) findViewById(R.id.bt_corelogin);
        image_btn=(ImageButton)findViewById(R.id.user_btn_img);

        edit_username=(EditText) findViewById(R.id.user_name);
        edit_password=(EditText) findViewById(R.id.user_pass);
        edit_phone=(EditText)findViewById(R.id.ed_phone); //你的手机号
        edit_cord=(EditText)findViewById(R.id.ed_code);//你的验证码

        bt_login.setOnClickListener(this);
        bt_register.setOnClickListener(this);
        bt_getphonecore.setOnClickListener(this);
        bt_corelogin.setOnClickListener(this);
        image_btn.setOnClickListener(this);

        uService = new UserService(LoginActivity.this);

        usernamelList = uService.getAll();

    }

    protected void onDestroy() {//销毁
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);

    }

    protected void onResume() {
        super.onResume();
        usernamelList.clear();      //从注册返回时清除usernamelList
        usernamelList = uService.getAll(); //更新注册的内容
    }


    private void showListPopulWindow() {

        listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<String>(this,R.layout.list_item, usernamelList));//用android内置布局,或设计自己的样式
        listPopupWindow.setAnchorView(edit_username);//以哪个控件为基准,在该处以mEditText为基准
        listPopupWindow.setModal(true);

        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {//设置项点击监听
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                edit_username.setText(usernamelList.get(i));//把选择的选项内容展示在EditText上
                listPopupWindow.dismiss();//如果已经选择了,隐藏起来
            }

        });

        listPopupWindow.show();//把ListPopWindow展示出来
    }






    //按钮点击事件
    @Override
    public void onClick(View v) {
/*
        String phone_number=edit_phone.getText().toString();//1
        String cord_number=bt_getcord.getText().toString().trim();//1
*/

        switch (v.getId()){
            case R.id.bt_login://登录监听
                String name=edit_username.getText().toString();
                String pass=edit_password.getText().toString();
                boolean flag=uService.login(name, pass);
                if(flag){
                    Log.i("TAG","登录成功");
                    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                }else{
                    Log.i("TAG","登录失败");
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.bt_register://注册监听
                Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_getphonecore://获取验证码的ID
                if(judPhone()){//去掉左右空格获取字符串,是正确的手机号
                    SMSSDK.getVerificationCode("86",phone_number);//获取你的手机号的验证码
                    edit_cord.requestFocus();//判断是否获得焦点
                }
                break;
            //  获取后要提交你的验证码以判断是否正确,并登陆成功
            case R.id.bt_corelogin://登陆页面的ID
                if(judCord()) {//判断验证码
                    SMSSDK.submitVerificationCode("86", phone_number, cord_number);//提交手机号和验证码
                    startActivity(new Intent(this,MainActivity.class));
                }
                coreflag=false;
                break;
            case R.id.user_btn_img://编辑框下拉监听
                showListPopulWindow(); //调用显示PopuWindow 函数
                break;
        }
    }

    private boolean judPhone() {//判断手机号是否正确
        //不正确的情况
        if(TextUtils.isEmpty(edit_phone.getText().toString().trim()))//对于字符串处理Android为我们提供了一个简单实用的TextUtils类,如果处理比较简单的内容不用去思考正则表达式不妨试试这个在android.text.TextUtils的类,主要的功能如下:
        //是否为空字符 boolean android.text.TextUtils.isEmpty(CharSequence str)
        {
            Toast.makeText(LoginActivity.this,"请输入您的电话号码",Toast.LENGTH_LONG).show();
            edit_phone.requestFocus();//设置是否获得焦点。若有requestFocus()被调用时,后者优先处理。注意在表单中想设置某一个如EditText获取焦点,光设置这个是不行的,需要将这个EditText前面的focusable都设置为false才行。
            return false;
        }
        else if(edit_phone.getText().toString().trim().length()!=11){
            Toast.makeText(LoginActivity.this,"您的电话号码位数不正确",Toast.LENGTH_LONG).show();
            edit_phone.requestFocus();
            return false;
        }

        //正确的情况
        else{
            phone_number=edit_phone.getText().toString().trim();
            String num="[1][3578]\\d{9}";
            if(phone_number.matches(num)) {
                return true;
            }
            else{
                Toast.makeText(LoginActivity.this,"请输入正确的手机号码",Toast.LENGTH_LONG).show();
                return false;
            }
        }
    }


    private boolean judCord() {//判断验证码是否正确
        judPhone();//先执行验证手机号码正确与否
        if(TextUtils.isEmpty(edit_cord.getText().toString().trim())) {//验证码
            Toast.makeText(LoginActivity.this, "请输入您的验证码", Toast.LENGTH_LONG).show();
            edit_cord.requestFocus();//聚集焦点
            return false;
        }
        else if(edit_cord.getText().toString().trim().length()!=4){
            Toast.makeText(LoginActivity.this,"您的验证码位数不正确",Toast.LENGTH_LONG).show();
            edit_cord.requestFocus();
            return false;
        }
        else{
            cord_number=edit_cord.getText().toString().trim();
            return true;
        }
    }

    public void sms_verification(){
        //MobSDK.init(context, "28bc12fa236e4","44cb357655f252a8a75eac378b8283ad");
        eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                Message msg=new Message();//创建了一个对象
                msg.arg1=event;
                msg.arg2=result;
                msg.obj=data;
                handler.sendMessage(msg);
            }
        };

        SMSSDK.registerEventHandler(eventHandler);//注册短信回调(记得销毁,避免泄露内存)*/
    }

    /**
     * 使用Handler来分发Message对象到主线程中,处理事件
     */
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event=msg.arg1;
            int result=msg.arg2;
            Object data=msg.obj;
            if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {//获取验证码成功
                if(result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    boolean smart = (Boolean)data;
                    if(smart) {
                        Toast.makeText(getApplicationContext(),"该手机号已经注册过,请重新输入",Toast.LENGTH_LONG).show();
                        edit_phone.requestFocus();//焦点
                        return;
                    }
                }
            }
            //回调完成
            if (result==SMSSDK.RESULT_COMPLETE){
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
                    Toast.makeText(getApplicationContext(), "验证码输入正确",Toast.LENGTH_LONG).show();
                }
            }else {//其他出错情况
                if(coreflag){
                    bt_getphonecore.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(),"验证码获取失败请重新获取", Toast.LENGTH_LONG).show();
                    edit_phone.requestFocus();
                }
                else{
                    Toast.makeText(getApplicationContext(),"验证码输入错误", Toast.LENGTH_LONG).show();
                }

            }
        }

    };

}

添加 Appkey 与 App Secret

  • AndroidManifest.xml中增加
<meta-data android:name="Mob-AppKey" android:value="xxx"/>
<meta-data android:name="Mob-AppSecret" android:value="xxx"/>

还要把需要的权限增加进去

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

完整的

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.syydnrycx.sqlitelogin">

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Activity.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Activity.RegisterActivity">
        </activity>

        <activity android:name=".Activity.MainActivity">
        </activity>

        <activity
            android:name="com.mob.tools.MobUIShell"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:windowSoftInputMode="stateHidden|adjustResize"/>

        <meta-data android:name="Mob-AppKey" android:value="xxx"/>

        <meta-data android:name="Mob-AppSecret" android:value="xxx"/>

    </application>

</manifest>

  • 主要的注释在代码中都有体现,还有一些代码没有贴出来可以在我的Github上下载下来看。

最后附上我的博客!!!

相关文章

  • Android开发-注册登录与手机验证登录

    效果图 前言 这篇主要讲如何通过数据库添加用户注册账户并且验证账户并且登录,还可以通过手机接收验证码登录。 准备 ...

  • Axure操作一:注册登录页

    系统应用常见的注册登录方式有:手机+验证码、手机+密码、手机+验证码+密码。比较古早的注册登录方式也有直接使用ID...

  • 硅谷外卖项目day03

    day03 项目地址 一、完成登录注册功能 2种登录方式手机号/验证码登录用户名/密码/图片验证码登录 登录的基本...

  • 经验

    随遇 手机上的app无需区分登录或者注册 直接输入手机号 发送验证短信 即可。有账号登录,无账号注册后登录。 of...

  • 登录注册流程还原—「达目标」

    一、「手机号验证码注册登录」 二、「手机号密码登录」 三、「忘记密码——手机号重置」

  • iOS开发--passport

    1. 注册/登录环节流程: 选择微信/微博/QQ/手机--(选择手机)输入电话号码(系统自动验证用户需要注册/登录...

  • 白日梦APP接口示例

    常规APP接口示例 已添加接口 发送登录验证码 手机号登录/注册 微信号登录/注册 获取用户详细信息 常规配置 每...

  • 开发第一步 短信验证码登录

    Android 开发第一步 短信验证码登录

  • day51-Django项目-天天生鲜

    一、注册模块 1.创建注册验证表单 2.注册功能 二、登录模块 1.创建登录验证表单 2.登录功能 三、中间件校验...

  • Android注册时总是出现"验证码不正确"

    【背景】在登录注册界面 往往存在验证码 功能,注册或者登录的时候,将手机号码,验证码,密码一并提 交到后台。这个时...

网友评论

    本文标题:Android开发-注册登录与手机验证登录

    本文链接:https://www.haomeiwen.com/subject/qaywqqtx.html