友链:汪菜菜

友链:隔壁老王

LoginActivity

package com.example.wms;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.example.wms.entity.LoginEntity;
import com.example.wms.entity.json.Info_c;
import com.example.wms.util.HttpHelper;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Set;

public class LoginActivity extends BaseNfcActivity {

    public String str_username;
    private String str_password;
    private EditText mEditText_username;
    private EditText mEditText_password;
    private Button mButton_login;
    private String result = "";
    LoginEntity loginEntity = new LoginEntity();
    Info_c info_c = new Info_c();
    private Intent intent_temp;
    private String loginErrorMsg="";//登录消息
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //设置为全局变量
        mEditText_username = (EditText) findViewById(R.id.edit_username);
        mEditText_password = (EditText) findViewById(R.id.edit_password);
        //兼容性
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            //继承后自动创建对应的布局界面
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);

            //绑定控件
            mEditText_username = findViewById(R.id.edit_username);
            mEditText_password = findViewById(R.id.edit_password);
            mButton_login = findViewById(R.id.btn_login);

            //登录按钮点击事件
            mButton_login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //获取输入框中的值 返回该对象的字符串表示
                    str_username = mEditText_username.getText().toString();
                    str_password = mEditText_password.getText().toString();
                    if(str_username.equals("")){
                        loginErrorMsg="用户名不能为空";
                        Toast.makeText(LoginActivity.this,loginErrorMsg, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(str_password.equals(""))
                    {
                        loginErrorMsg="密码不能为空";
                        Toast.makeText(LoginActivity.this,loginErrorMsg, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    progressDialog = new ProgressDialog(LoginActivity.this);
                    progressDialog.setTitle("CATL");
                    progressDialog.setMessage("正在登录,请稍等......");
                    progressDialog.setIndeterminate(true);
                    progressDialog.setCancelable(false);
                    progressDialog.show();

                    new Thread(new Runnable(){
                        public  void run(){
                            try{
                                //此处执行业务逻辑,测试用延时模拟
                                Login(str_username,str_password);
                                Message msg=new Message();
                                msg.what=1;
                                HttpHelper.handler.sendMessage(msg);

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }).start();

                    HttpHelper.handler=new Handler(){
                        public void handleMessage(Message msg) {
                            try {
                                if(progressDialog!=null){
                                    progressDialog.dismiss();

                                    if(loginErrorMsg.equals("")){
                                        Intent intent1 = new Intent(LoginActivity.this, MainActivity.class);
                                        Toast.makeText(LoginActivity.this, "登录成功,欢迎您\t" + str_username, Toast.LENGTH_LONG).show();
                                        startActivity(intent1);//跳转到z界面
                                    }else{
                                        Toast.makeText(LoginActivity.this,loginErrorMsg, Toast.LENGTH_SHORT).show();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };

            }});
        }


    }

    @Override
    public void onNewIntent(Intent intent) {
        intent_temp=intent;
        //获取Tag对象
        super.onNewIntent(intent);
        String icCardString = readNFCAData(intent_temp);
        //界面用户框中显示用户卡号√
        mEditText_username.setText(icCardString);
        mEditText_password.setText(icCardString);

        progressDialog = new ProgressDialog(LoginActivity.this);
        progressDialog.setTitle("CATL");
        progressDialog.setMessage("正在登录,请稍等......");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(false);
        progressDialog.show();

        new Thread(new Runnable(){
            public void run(){
                try {
                    Login(icCardString,icCardString);
                    Message msg=new Message();
                    msg.what=0;
                    HttpHelper.handler.sendMessage(msg);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

        HttpHelper.handler=new Handler(){
            public void handleMessage(Message msg) {
                try {

                    if(progressDialog!=null){
                        progressDialog.dismiss();

                        if(loginErrorMsg.equals("")){
                            Intent intent1 = new Intent(LoginActivity.this, MainActivity.class);
                            Toast.makeText(LoginActivity.this, "登录成功,欢迎您\t" + str_username, Toast.LENGTH_LONG).show();
                            finish();
                            startActivity(intent1);//跳转到z界面

                        }else{
                            Toast.makeText(LoginActivity.this,loginErrorMsg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };




    }

    public  void Login(String userName,String password){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //调用登录接口:传递参数用户名和密码。
        loginEntity.setUsername("admin");
        loginEntity.setPassword("bz.wms");
        //实体类转化为JSON
        Gson gson = new Gson();
        String value = gson.toJson(loginEntity);
        JSONObject root = new JSONObject();
        HttpHelper.AppDeviceNo = getLocalMacAddressFromIp();
        HttpHelper.IPAddress = getLocalInetAddress().toString().substring(1);
        try {
            //存data的值
            root.put("EncryptTokenNo", "");
            root.put("AppDeviceNo", HttpHelper.AppDeviceNo);
            root.put("IPAddress", HttpHelper.IPAddress);
            root.put("JsonData", value);
            root.put("apptype", HttpHelper.AppType);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //调用PostInfo方法将返回的值存放在result中
        result = PostInfo(root.toString());

        //创建一个最大的JSONObject去处result
        try {
            JSONObject jsonObjectALL = new JSONObject(result);
            String code = jsonObjectALL.optString("code", null);
            String baseinfo = jsonObjectALL.optString("info", null);
            String data = jsonObjectALL.optString("data", null);

            //判断接口状态,正确则跳转主界面,失败弹出提示框说明
            if (code.equals("1")) {
                if (!TextUtils.isEmpty(data)) {
                    JSONObject jsonObjectData = new JSONObject(data);

//                   String info = jsonObjectData.optString("baseinfo", null);
//                   JSONObject jsonObject = new JSONObject(info);

                    info_c = new Info_c();
                    info_c.setID(jsonObjectData.optString("ID", null));
                    info_c.setUserNo(jsonObjectData.optString("UserNo", null));
                    info_c.setUserPwd(jsonObjectData.optString("UserPwd", null));
                    info_c.setUserRoleId(jsonObjectData.optString("UserRoleId", null));
                    info_c.setUserNameBySimple(jsonObjectData.optString("UserNameBySimple", null));
                    info_c.setUserNameByChinese(jsonObjectData.optString("UserNameByChinese", null));
                    info_c.setUserNameByEnglish(jsonObjectData.optString("UserNameByEnglish", null));
                    info_c.setUserPhone(jsonObjectData.optString("UserPhone", null));
                    info_c.setUserQQ(jsonObjectData.optString("UserQQ", null));
                    info_c.setUserEmail(jsonObjectData.optString("UserEmail", null));
                    info_c.setUserWC(jsonObjectData.optString("UserWC", null));
                    info_c.setUserAddress(jsonObjectData.optString("UserAddress", null));
                    info_c.setUserSex(jsonObjectData.optString("UserSex", null));
                    info_c.setUserType(jsonObjectData.optString("UserType", null));
                    info_c.setStatus(jsonObjectData.optInt("Status", 0));
                    info_c.setAddUserNo(jsonObjectData.optString("AddUserNo", null));
                    info_c.setAddTime(jsonObjectData.optString("AddTime", null));
                    info_c.setEditUserNo(jsonObjectData.optString("EditUserNo", null));
                    info_c.setEditTime(jsonObjectData.optString("EditTime", null));
                    info_c.setRemark(jsonObjectData.optString("Remark", null));
                    info_c.setLoginMsg(jsonObjectData.optString("LoginMsg", null));
                    info_c.setLoginOk(jsonObjectData.optBoolean("LoginOk"));
                    info_c.setAppType(jsonObjectData.optInt("AppType", 0));
                    info_c.setLoginTime(jsonObjectData.optString("LoginTime", null));
                    info_c.setEncryptTokenNo(jsonObjectData.optString("EncryptTokenNo", null));
                    HttpHelper.EncryptTokenNo = jsonObjectData.optString("EncryptTokenNo", null);
                }
            }else{
                loginErrorMsg="登录接口返回失败,消息:"+baseinfo;
            }
        } catch (JSONException e) {
            loginErrorMsg="登录异常";
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        if(HttpHelper.handler!=null){
            HttpHelper.handler.removeCallbacksAndMessages(null);
        }
    }

    //读取nfca类型的卡号
    public String readNFCAData(@NonNull Intent intent) {
        //获取Tag对象
        StringBuilder sb = new StringBuilder();
        Bundle datas = intent.getExtras();
        Set<String> keys = datas.keySet();
        for (String key : keys) {
            if ("android.nfc.extra.ID".equals(key)) {
                String data = byteArrayToHex((byte[]) datas.get(key));
                String replaceSpace = getReverseStr(data);
                sb.append(Long.parseLong(replaceSpace, 16));
            }
        }
        return sb.toString();
    }

    private String getReverseStr(String data) {
        String[] icStrSub = data.split(" ");
        StringBuilder myResult = new StringBuilder();
        for (int i = icStrSub.length - 1; i >= 0; i--) {
            myResult.append(icStrSub[i]);
        }
        return myResult.toString();
    }

    private String byteArrayToHex(byte[] bytes) {
        StringBuffer sBuffer = new StringBuffer();
        for (byte b : bytes) {
            int hexInt = b < 0 ? 256 + b : b;
            if (hexInt < 10) {
                sBuffer.append("0" + Integer.toHexString(hexInt) + " ");
            } else {
                sBuffer.append(Integer.toHexString(hexInt) + " ");
            }
        }
        return sBuffer.toString().toUpperCase();
    }

    protected String PostInfo(String json) {
        //Setting_Activity.SDcard();
        //String url= HttpHelper.BASE_URL+methedName;
        return HttpHelper.Post(HttpHelper.url_Login, json);
    }

    private static String getLocalMacAddressFromIp() {

        String strMacAddr = null;
        try {
            //获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {

        }
        return strMacAddr;
    }

    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            //列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }
                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip;
    }
}

 

posted @ 2022-06-08 10:38  長安憶ღ  阅读(81)  评论(0)    收藏  举报