안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji

코드 한 줄

사용자 환경 : macOS Sierra 10.12.6Android Studio 3.0.1 {

  Build #AI-171.4443003, built on November 10, 2017

  JRE: 1.8.0_152-release-915-b08 x86_64

  JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

  }

현재 로그인 시스템이 구현되어 있는 대부분의 앱에는 자동 로그인 기능이 구현되어 있다.

자동 로그인 기능이 구현되어 있지 않은 앱을 사용해본 경험이 있다면 이 기능을 사용함으로써 앱이 많은 편리함을 가져다 준다는 것을 알 수 있다.

이 기능을 구현하기 위해 우리는 SharedPreference API를 사용할 것이다.

1. 가장 먼저 정보를 저장하기 위한 메소드를 내장한 클래스를 구현한다.

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class SaveSharedPreference {

    static final String PREF_USER_NAME = "username";

    static SharedPreferences getSharedPreferences(Context ctx) {
        return PreferenceManager.getDefaultSharedPreferences(ctx);
    }

    // 계정 정보 저장
    public static void setUserName(Context ctx, String userName) {
        SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
        editor.putString(PREF_USER_NAME, userName);
        editor.commit();
    }

    // 저장된 정보 가져오기
    public static String getUserName(Context ctx) {
        return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
    }

    // 로그아웃
    public static void clearUserName(Context ctx) {
        SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
        editor.clear();
        editor.commit();
    }
}

line 7. key 값에 해당된다.

line 9~11. 모든 액티비티에서 인스턴스를 얻기 위한 메소드이다.

line 14~18. 로그인 시 자동 로그인 여부에 따라 호출 될 메소드이다. userName이 저장된다.

line 21~23. 현재 저장된 정보를 가져오기 위한 메소드이다.

line 26~30. 자동 로그인 해제 및 로그아웃 시 호출 될 메소드이다.

2. 자동 로그인 여부를 체크할 인증용 액티비티 생성.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class FirstAuthActivity extends AppCompatActivity {

    private Intent intent;

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

        if(SaveSharedPreference.getUserName(FirstAuthActivity.this).length() == 0) {
            // call Login Activity
            intent = new Intent(FirstAuthActivity.this, LoginActivity.class);
            startActivity(intent);
            this.finish();
        } else {
            // Call Next Activity
            intent = new Intent(FirstAuthActivity.this, HomeActivity.class);
            intent.putExtra("STD_NUM", SaveSharedPreference.getUserName(this).toString());
            startActivity(intent);
            this.finish();
        }
    }
}

line 15~20. SharedPreference에 저장되어 있는 정보의 길이가 0일 경우, 즉 없을 경우 로그인 액티비트를 호출한다.

line 20~26. 나머지 경우, 즉 저장되어 있는 정보가 있을 경우 바로 로그인 다음 액티비티를 호출한다.

3. 자동 로그인 설정 시 사용할 코드

SaveSharedPreference.setUserName(LoginActivity.this, editId.getText().toString());

로그인 액티비티에서 자동 로그인 설정과 함께 로그인 시 EditText의 값을 SaveSharedPrefernce.setUserName(Context, String) 메소드를 통해 저장.

Tag Android, Java, Login, Mac, preference, shared, studio, svae, 로그인, 안드로이드, 저장, 정보

안드로이드 복습

안드로이드 자동 로그인 SharedPreferences

초보보 혜진 2021. 9. 2. 17:29

안드로이드 자동 로그인을 알아둬야 할 것 같아

구글링해서 한 블로그의 글을 보고 참고해서 복습했다! 

1. SharedPreferences 사용하는 이유 

개발을 하다보면 자동로그인처럼 앱의 데이터들을 저장해서 관리해야하는 상황이 있다. 

데이터의 양이 많다면 db에 저장을 하면 되지만 간단한 데이터들을 db에 넣기 애매한 상황들이 있다. 

이런 경우에 SharedPreferences를 사용하면 편리하게 관리할 수 있다!

SharedPreferences는 데이터를 파일로 저장한다고 한다. 

그래서 파일의 앱 폴더내에 저장되기 때문에 앱이 삭제되면 데이터도 당연히 삭제된다. 

2. 간단한 자동로그인 구현하기 

이제 SharedPreferences를 이용해 간단한 자동로그인을 구현할 것이다! 

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji
Login화면

1) xml 레이아웃에 이런 식으로 로그인 화면을 만든다. 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".LoginExample">

    <EditText
        android:id="@+id/et_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="47dp"
        android:ems="10"
        android:hint="아이디를 입력하세요."
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="@+id/textView2"
        app:layout_constraintStart_toEndOf="@+id/textView2" />

    <EditText
        android:id="@+id/et_pwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="17dp"
        android:ems="10"
        android:hint="비밀번호를 입력하세요."
        android:inputType="textPassword"
        app:layout_constraintBottom_toBottomOf="@+id/textView3"
        app:layout_constraintEnd_toEndOf="@+id/et_id"
        app:layout_constraintStart_toEndOf="@+id/textView3" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="66dp"
        android:layout_marginTop="219dp"
        android:text="ID"
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="PWD"
        android:textSize="24sp"
        app:layout_constraintStart_toStartOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="Login"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_pwd" />
</androidx.constraintlayout.widget.ConstraintLayout>

2) 로그인하고 들어가는 sub화면도 만들어준다. 

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji
로그인 후 화면
안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji

3) java 파일 작성

- 자동 로그인 

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji

getSharedPreferences()  메서드를 통해서 SharedPreferences객체를 받아 올 수 있다. 

-name은 SharedPreferences의 이름으로 특정 이름으로 생성할 수 있고, 해당 이름으로 xml 파일이 생성된다고 생각하면 된다. 

-mode는 읽고 쓰기 권한 관련된 것으로 Mode_private 는 생성한 application에서만 사용 가능한 것이라고 한다. 

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji

SharedPreferences 객체를 통해 원하는 값의 key와 디폴트 값을 파라미터로 하여 호출하면 간단하게 값을 받아 올 수 있다. 

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji

값을 받아 저장한 loginId와 loginPwd의 값이 null이 아니고, id와 pwd 값이 정해진 값이라면 기존에 로그인을 한번 했다는 뜻이기 때문에 자동로그인으로 넘어간다. 

(여기선 db를 사용하고 있지 않기 때문엔 그냥 임시로 id와 pwd를 설정해줬다!

비밀번호는 알아서 설정하세유) 

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji

만약 loginId와 loginPwd에 값이 null라면 로그인을 한번도 안했던 사용자이기 때문에 로그인하기 위해 아이디와 비밀번호를 입력한다.

그리고 이에 대한 값을 String으로 받아온 값들이 정해놓은 id와 pwd로 같다면 SharedPreferences 객체를 생성하고 데이터를 저장하기 위해 Editor 객체를 받아 온다. 

Editor 객체인 autoLogin에 원하는 값을 key, value 형태로 입력하고 

commit()을 통해서 완료하면 데이터 저장은 완료된다! 

-> commit() 꼭 해야한다고 함 

- 로그아웃

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji

두번째 액티비티에서 Logout 버튼을 누르면 자동로그인이 풀리게 된다. 

SharedPreferences에 저장된 값들을 로그아웃하면 삭제하기 위해서 SharedPreferences 객체를 불러옵니다.

Editor 객체를 통해 저장된 데이터를 가져오고,

editor.clear() 을 통해 eidtor에 들어있던 모든 정보를 기기에서 지웁니다.

그리고 editor.commit()을 해서 저장합니다. 

그러면 로그아웃이 된다!

안드로이드 앱 로그인 유지 - andeuloideu aeb logeu-in yuji
자동로그인 실행 결과 

-> 자동로그인 실행 결과! 

이렇게 간단하게 자동로그인을 구현할 수 있다.

이 방법을 프로젝트에 사용할지는 잘 모르겠지만 알아두기 ㅇㅁㅇ 

-Login 

package com.example.myapplication4;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginExample extends AppCompatActivity {

    EditText et_id, et_pwd;
    Button btn_login;
    
    String loginId,loginPwd;

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

        et_id = findViewById(R.id.et_id);
        et_pwd = findViewById(R.id.et_pwd);
        btn_login = findViewById(R.id.btn_login);

        SharedPreferences sharedPreferences = getSharedPreferences("sharedPreferences", Activity.MODE_PRIVATE);
        
        loginId = sharedPreferences.getString("inputId", null);
        loginPwd = sharedPreferences.getString("inputPwd", null);
        
        if(loginId != null && loginPwd != null) {
            if(loginId.equals("hj") && loginPwd.equals("xxxx")) {
                Toast.makeText(getApplicationContext(), loginId + "님 자동로그인 입니다!", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(getApplicationContext(), LoingSubExample.class);
                intent.putExtra("id", loginId);
                startActivity( intent);
                finish();
            }
        }else if(loginId == null && loginPwd == null) {
            btn_login.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (et_id.getText().toString().equals("hj") && et_pwd.getText().toString().equals("xxxx")) {
                        SharedPreferences sharedPreferences = getSharedPreferences("sharedPreferences", Activity.MODE_PRIVATE);

                        SharedPreferences.Editor autoLogin = sharedPreferences.edit();

                        autoLogin.putString("inputId", et_id.getText().toString());
                        autoLogin.putString("inputPwd", et_pwd.getText().toString());

                        autoLogin.commit();
                        Toast.makeText(getApplicationContext(), et_id.getText().toString()+"님 환영합니다.", Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent(getApplicationContext(), LoingSubExample.class);
                        startActivity(intent);
                        finish();
                    }
                }
            });
        }

    }
}

- sub

package com.example.myapplication4;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class LoingSubExample extends AppCompatActivity {

    TextView tv_userId;
    Button btn_logout;


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

        tv_userId = findViewById(R.id.tv_userId);
        btn_logout = findViewById(R.id.btn_logout);

        Intent intent  = getIntent();
        String id = intent.getExtras().getString("id");
        tv_userId.setText(id);

        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), LoginExample.class);
                startActivity(intent);

                SharedPreferences sharedPreferences = getSharedPreferences("sharedPreferences", Activity.MODE_PRIVATE);

                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.clear();
                editor.commit();

                Toast.makeText(getApplicationContext(), "로그아웃", Toast.LENGTH_SHORT).show();

                finish();
            }
        });
    }
}