admin管理员组

文章数量:1616685

AndroidStudio与后台实现登录(安卓端操作)

  • 配置环境
    • AndroidManifest
    • build.gradle(:app)
  • AS主要代码
    • xml布局
    • java代码

版本 AS 4.0.2

配置环境

AndroidManifest

在manifest里面 application外面添加以下代码段

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

第一行internet用来申请网络权限
第二行write_external_storage用来申请应用在外部存储设备中写入和修改文件的权限

build.gradle(:app)

在我的项目里面版本如下 供参考

compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.example.logindemo"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

在dependence里面导入

implementation("com.squareup.okhttp3:okhttp:4.2.0")
implementation 'com.google.code.gson:gson:2.7'
implementation 'com.alibaba:fastjson:1.2.44'

因为要用到okhttp 第一行导入okhttp 目前我找到能使用的版本是okhttp3的4.2.0
第二行导入谷歌的gson包
第三行导入阿里的fastjson包
后面两个我目前也不知道是不是必要的 但确实解决了我关于responseData为空的bug

AS主要代码

xml布局

贴上我的xml布局 很简单

然后登录成功的话就跳转到下面的页面

因为是个小demo 做的比较简陋 大概就是这样子的
因为我比较体贴 这是一个小白教程嘿嘿嘿 贴上代码段 当然如果看到上面的展示图觉得简单的话直接就可以跳过下面的代码啦

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android/apk/res/android"
    xmlns:app="http://schemas.android/apk/res-auto"
    xmlns:tools="http://schemas.android/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">


        <EditText
            android:id="@+id/userName"
            android:layout_width="300dp"
            android:layout_height="50dp"
            android:hint="用户名"
            android:layout_marginLeft="50dp"
            />
        <EditText
            android:id="@+id/passWord"
            android:layout_marginTop="20dp"
            android:layout_width="300dp"
            android:layout_height="50dp"
            android:layout_marginLeft="50dp"
            android:hint="密码"/>

        <Button
            android:id="@+id/btn_Login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登录"
            android:gravity="center"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="100dp"
            android:layout_marginTop="20dp"/>

    </LinearLayout>


</RelativeLayout>

第二个页面也只是一个TextView

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to Activity2"
    android:layout_centerInParent="true"/>

java代码

真正让我琢磨了很久的地方
首先绑定了布局和控件
在触发按钮之后

public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_Login:
                //trim是啥用
                username = edit_userName.getText().toString().trim();
//                System.out.println(username+"我是username");
                password = edit_passWord.getText().toString().trim();
//                System.out.println(password+"我是password");
                sendRequestWithOkHttp(username, password, this);
                break;
        }
    }

获得EditText的文本内容
trim() 方法用于删除字符串的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等,不改变字符串的内容.
sendRequestWithOkHttp是用来建立网络连接的方法,传入获得的用户名和密码,将数据传送给后台,在我这个做法里,后台直接帮我判断了数据是否匹配。

private void asyncGetOtpCodeWithXHttp(final String username, final String password, final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String tag = null;
                Log.d(tag, "???");//这个是我用来测试这个方法有没有跑的代码
                OkHttpClient client = new OkHttpClient();
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody requestBody = new FormBody.Builder()
                        .add("username", username)
                        .add("password", password)
                        .build();
                Request request = new Request.Builder()
                        .url("http://yslgdym/tp5/public/index.php/login")//这个是与我合作的后台 具有我注册过的账号密码的信息并且返回一个判断数值
                        .post(requestBody)
                        .build();
                try{
                    Response response = client.newCall(request).execute();
                    responseData = response.body().string();
                    System.out.println("我是responseData"+responseData);//这是我用来查看返回值的代码 进行对比
                } catch (IOException e) {
                    e.printStackTrace();
                }
                switch (responseData){
                    case "1":
                        Looper.prepare();
//                        showToastInThread(LoginActivity.this,"登录成功!");
                        Toast.makeText(context, "登录成功!" , Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(context, MainActivity2.class);
                        startActivity(intent);
                        Looper.loop();
                        break;
                    case "3":
                        showToastInThread(context,"不是POST传值");
//                        Toast.makeText(context,  "不是POST传值", Toast.LENGTH_SHORT);
                        break;
                    case "0":
                        showToastInThread(context,"密码错误");
//                        Toast.makeText(context,  "密码错误", Toast.LENGTH_SHORT);
                        break;
                    case "5":
                        showToastInThread(context,"用户不存在");
//                        Toast.makeText(context,  "用户不存在", Toast.LENGTH_SHORT);
                        break;
                    case "10":
                        showToastInThread(context,"密码长度错误、用户名长度错误");
//                        Toast.makeText(context,  "用户不存在", Toast.LENGTH_SHORT);
                        break;
                    default:
                        break;
                }

            }
        }).start();
    }
private void showToastInThread(Context context,String string) {
        Looper.prepare();
        Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }

要特别声明的是 使用OKhttp要开一个新的线程 不然会报错 以免造成线程堵塞的情况(网络连接啥的需要时间嘛对不)
我与后台协商好之后 根据返回来的不同值 就知道了各个返回值代表的情况 然后我用一个switch方法去匹配不同操作
注意!在子线程中不能直接用toast 会报错(血与泪的教训,好像是因为toast的show方法用了handler,而handler不能在子线程中直接使用,要有looper
在前辈的指导下 我在showToastInThread()方法里面用looper使toast呈现出来。
大概就是这样子啦。

本文标签: 后台操作AndroidStudio安卓端