AndroidStudio and background to achieve login (Android terminal operation)

AndroidStudio and background to achieve login (Android terminal operation)


Version AS 4.0.2

Configuration Environment

AndroidManifest

Add the following code segment outside the application in the manifest

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

The first line internet is used to apply for network permission
The second line write_external_storage is used to apply for the permission of the application to write and modify files in the external storage device

build.gradle(:app)

The version in my project is as follows for reference

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"
    }

Import in dependency

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

Because you need to use okhttp. The first line imports okhttp. Currently, I found that the version that can be used is 4.2.0 of okhttp3. The
second line imports Google’s gson package.
The third line imports Ali’s fastjson package.
I don’t know if it’s necessary. But it did solve my bug about responseData being empty
insert image description here

AS main code

xml layout

It’s very simple to paste my xml layout.
insert image description here
Then, if you log in successfully, you will jump to the following page
insert image description here
because it’s a small demo. It’s relatively crude and probably like this
because I’m more considerate. This is a tutorial for novices. If you see the above display and think it is simple, you can skip the following code directly.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/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>

The second page is also just a TextView

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

java code

The place that really made me think about it for a long time
first bound the layout and controls
after triggering the button

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;
        }
    }

Get the text content of EditText.
The trim() method is used to delete the leading and trailing blanks of the string. The blanks include: spaces, tabs, newlines and other blanks, etc., without changing the content of the string. sendRequestWithOkHttp is used
to The method of establishing a network connection is to pass in the obtained user name and password, and transmit the data to the background. In my method, the background directly helps me judge whether the data matches.

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.cn/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();
    }

What I want to declare is that you need to open a new thread to use OKhttp, otherwise you will report an error to avoid thread blockage (the network connection takes time, right?) After negotiating with the background, I know each return according to the different values ​​returned
. The value represents the situation and then I use a switch method to match different operations
Note! If you can’t use toast directly in the sub-thread, an error will be reported (the lesson of blood and tears, it seems that because the show method of toast uses a handler, and the handler cannot be used directly in the sub-thread, there must be a looper. Under the guidance of the seniors, I will showToastInThread
( ) method uses looper to make the toast appear.
Probably like this.

Guess you like

Origin blog.csdn.net/weixin_51906150/article/details/118860985