Andrews terminal ## logged

Andrews terminal ## logged

(A) trigger a scene
in fact, visit the registration page for the user mishandling is a very poor user experience. We need to do more than just match the server connection account and password, but also to pay attention to the account information stored with App automatically logs and other conditions when opened.

(B) registration methods - phone number, email, third-party account number
1 mobile phone number registered. In fact, this is the most efficient registration methods, taking into account the input mode mobile terminal handover is required, in order to simplify user operation, the proposed mobile terminal only registered mobile phone number, so you can directly pop-up numeric keypad, users do not need conversion, but if the application is also there are PC side entrance should be noted that unification of the two. For example, a mobile phone is registered to provide end only way, then the PC side should have registered the phone registration and login, if the PC side retained the registered mail, then phone side should also provide operation binding the mailbox in the settings.

2 mail registration. E-mail registration methods should belong to the desktop registration mode is not suitable for mobile terminals. The reason is that the user can not ensure whether to install the appropriate mailbox or to know the phone side, there is a problem of convenience operation even installed, taking into account the registered phone verification code immediacy and verification code will appear in the status bar, users do not need nothing can get verification code received, and recommends priority to registered mobile terminal phone number. Sign In fact, the desktop operating gap between the two will be much smaller, but it comes to password security issues, it is recommended only if the registered phone number should alert the user mailbox binding in account security in order to recover your password.

3 third-party account. Although third-party landed convenient, but the general website, application or want to register a single user account, in fact, doing so for the vast majority of the site does not do any good, because users may forget these individual sites account had to register again, this is affecting the user's experience, and thus is not recommended unless specifically requested a separate account system.

FIG enclose effect
Here insert picture tree described above
then is a layout XML code

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:orientation="vertical"
    android:layout_height="420dp"
    android:layout_width="match_parent"
    android:layout_marginTop="100dp">


    <EditText
        android:layout_marginTop="120dp"
        android:id="@+id/username"
        android:layout_width="350dp"
        android:layout_gravity="center"
        android:layout_height="60dp"
        android:hint="用户名/手机号/邮箱"
        android:background="@drawable/background_edit_div"/>

    <EditText
        android:layout_marginTop="30dp"
        android:id="@+id/password"
        android:layout_width="350dp"
        android:layout_gravity="center"
        android:layout_height="60dp"
        android:hint="请输入您的密码"
        android:background="@drawable/background_edit_div"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="85dp"
        android:layout_marginTop="50dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:background="@drawable/background_button_div"
            android:text="登录"
            android:textColor="#646868"
            android:layout_marginLeft="130dp"
            android:textAlignment="center"
            android:textSize="18sp" />

        <Button
            android:id="@+id/register"
            android:layout_width="wrap_content"
            android:layout_height="60dp"
            android:layout_marginLeft="30dp"
            android:background="@drawable/background_button_div"
            android:text="注册"
            android:textColor="#646868"
            android:textAlignment="center"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>
Note: This background is the author of a custom property value, the reader can be modified according to other styles

接下来是Activity代码
public class LoginActivity extends Activity{
private LoginUserInfo loginUserInfo;
private EditText username;
private EditText password;
private Button login;
private Button register;
public static SharedPreferences sharedPreferences;
public static SharedPreferences.Editor editor;

//用于接收Http请求的servlet的URL地址,请自己定义
private String loginAddress = "http:***********";
//用于处理消息的Handler
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        String result = "";
        if ("200".equals(msg.obj.toString())){
            result = "登入成功";
            //使用sharePreferences保存该账号的登入状态
            editor.putString(loginUserInfo.getLoginUser_phoneNumber(),"1");
            editor.commit();
            Intent intent = new Intent(LoginActivity.this, App_MainActivity.class);
            startActivity(intent);
            LoginActivity.this.finish();
        }else if ("400".equals(msg.obj.toString())){
            result = "账号密码不匹配";
        }else {
            result = msg.obj.toString();
            Log.e("Http请求发生错误",result);
        }
        Log.w("Http请求状态",result);
        Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    loginUserInfo=(LoginUserInfo)getApplication();
    //在加载布局文件先查询是否登陆过
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences=this.getSharedPreferences("test",MODE_PRIVATE);
    editor = sharedPreferences.edit();
    //使用sharePreferences保存登入状态

    //后面的参数是当login_flag没有时的默认参数
    //使用迭代器遍历所有账号此时的登入状态
    Map<String,?>map=sharedPreferences.getAll();
    for (Map.Entry k:map.entrySet())
    {
        String value=sharedPreferences.getString(k.getKey().toString(),"0");
        if (value.equals("1"))
        {
            //这边还要再次去服务器请求用户数据才行
            //因为程序退出或者重装后LoginUserInfo已经没了
            AutoLoginHttpUtil autoLoginHttpUtil=new AutoLoginHttpUtil(loginUserInfo);
            Log.e("当前已经登入的账号手机号码为:",(String) k.getKey());
            autoLoginHttpUtil.RequestUserInfo((String) k.getKey());
            Intent intent = new Intent(LoginActivity.this, App_MainActivity.class);
            startActivity(intent);
            LoginActivity.this.finish();
        }
    }

    setContentView(R.layout.login);
    username = (EditText) findViewById((R.id.username));
    password = (EditText) findViewById(R.id.password);
    login =    (Button) findViewById(R.id.login);
    register = (Button) findViewById(R.id.register);
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Servlet_login();
        }
    });
}

 public void Servlet_login ()
    {
        //构造HashMap
        HashMap<String, String> params = new HashMap<String, String>();
        String tmp= username.getText().toString();
        params.put(User.PHONENUMBER,tmp);
        params.put(User.PASSWORD, password.getText().toString());
        if (tmp.equals(""))
        {
            Toast.makeText(LoginActivity.this,"请输入手机号码",Toast.LENGTH_SHORT).show();
            return;
        } else if (tmp.length()!=11) {
            Toast.makeText(LoginActivity.this,"手机格式不正确",Toast.LENGTH_SHORT).show();
            return;
        }
        if (password.getText().toString().equals(""))
        {
            Toast.makeText(LoginActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            HttpUtil httpUtil=new HttpUtil(loginUserInfo);
            //构造完整URL
            //通过解析URL的附加参数(账号密码会附加在url中)来判断
            String compeletedURL = httpUtil.getURLWithParams(loginAddress, params);
            //发送请求
            httpUtil.sendHttpRequest(compeletedURL, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                Message message = new Message();
                message.obj = response;
                mHandler.sendMessage(message);
                }

                @Override
                public void onError(Exception e) {
                Message message = new Message();
                message.obj = e.toString();
                mHandler.sendMessage(message);
                }
                @Override
                public void onFail(String response) {
                    Message message = new Message();
                    message.obj = response;
                    mHandler.sendMessage(message);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Primarily using the summary sharePreferences save login state all accounts, the automatic detection sharePreferences account login state all the APP open, if there is a detected account logged in login screen is skipped (It should be noted that although the saved sharePreferences signed in account, but down from the server cache account information has been cleared out when the program exits)
so we have the account information once again request to the server.
Similarly, when we do exit sign in the operation, should also be amended sharePreferences file and notification server.

这边再附上HTTP请求的代码
package com.example.strategyapp.HttpTool;
import com.example.strategyapp.LoginUserInfo;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {

private static LoginUserInfo loginUserInfo;
public HttpUtil(LoginUserInfo a)
{
    this.loginUserInfo=a;
}

//封装的发送请求函数
public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
    if (!HttpUtil.isNetworkAvailable()){
        //这里写相应的网络设置处理
        return;
    }
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection connection = null;
            try{
                URL url = new URL(address);
                //使用HttpURLConnection
                connection = (HttpURLConnection) url.openConnection();
                //设置方法和参数
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setInstanceFollowRedirects(false); //不自动处理重定向

                //获取返回结果
                InputStream inputStream = connection.getInputStream();
                byte[] data=new byte[1024];
                int len=0;
                ByteArrayOutputStream out=new ByteArrayOutputStream();
                //把response中的数据流写入字节组
                while ((len=inputStream.read(data))!=-1)
                {
                    out.write(data,0,len);
                }
                inputStream.close();
                //解析服务器返回Json字段并且传给监听器
               String jsonString=new String(out.toByteArray());
               boolean re=ParseJson(jsonString);
                //成功则回调onFinish
                if (re){
                    listener.onFinish("200");
                } else
                {
                    listener.onFail("400");
                }
            } catch (Exception e) {
                e.printStackTrace();
                //出现异常则回调onError
                if (listener != null){
                    listener.onError(e);
                }
            }finally {
                if (connection != null){
                    connection.disconnect();
                }
            }
        }
    }).start();
}

//解析登入时服务器发来的Json数据

public  static  boolean ParseJson(String jsonString)throws JSONException{
    JSONObject jsonObject=new JSONObject(jsonString);
    int code=jsonObject.getInt("code");
    if (code==400)
    {
        return false;
    }
    if (code==200)
    {
        JSONObject data=jsonObject.getJSONObject("data");
        loginUserInfo.setLoginUser_id(data.getInt("id"));
        loginUserInfo.setLoginUser_phoneNumber(data.getString("phoneNumber"));
        loginUserInfo.setLoginUser_name(data.getString("userName"));
        loginUserInfo.setLoginUser_avatar("http://10.0.2.2:8080/"+data.getString("avatar"));
        return true;
    }
    return false;
}

//组装出带参数的完整URL
public static String getURLWithParams(String address, HashMap<String,String> params)
        throws UnsupportedEncodingException {
    //设置编码
    final String encode = "UTF-8";
    StringBuilder url = new StringBuilder(address);
    url.append("?");
    //将map中的key,value构造进入URL中
    for(Map.Entry<String, String> entry:params.entrySet())
    {
        url.append(entry.getKey()).append("=");
        url.append(URLEncoder.encode(entry.getValue(), encode));
        url.append("&");
    }
   
    url.deleteCharAt(url.length() - 1);
    return url.toString();
}

//判断当前网络是否可用
public static boolean isNetworkAvailable(){
    //这里检查网络,后续再添加
    return true;
}

}

Written in the last
if wrong article, hope civilized exchange correction Hey ~

Published an original article · won praise 0 · Views 8

Guess you like

Origin blog.csdn.net/mkHarvey/article/details/105275634