라이브러리 주소 : https://github.com/google/gson

1
2
3
dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}
cs


안드로이드 스튜디오에 라이브러리 추가하기


1. 라이브러리 설치 Build.gradle(Module:app) Dependencies

1
2
    //구글 로그인 지원
    implementation 'com.google.android.gms:play-services-auth:12.0.0'
cs


2. https://console.firebase.google.com/ 사용설정으로 수정해준다.


3. LoginActivity.kr 페이지에 소스를 입력하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package kr.vrpano.wonstar
 
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Toast
import com.facebook.CallbackManager
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import kotlinx.android.synthetic.main.activity_login.*
 
class LoginActivity : AppCompatActivity() {
 
    // Firebase Authentication 관리 클래스
    var auth: FirebaseAuth? = null
 
    // 구글 로그인 관리 클래스
    var googleSignInClient: GoogleSignInClient? = null
 
//    // 로그인 처리 결과 관리 클래스
//    var callbackManager : CallbackManager? = null
 
    // GoogleLogin
    val GOOGLE_LOGIN_CODE = 9001
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
 
        // Firebase 로그인 통합 관리하는 Object 만들기
        auth = FirebaseAuth.getInstance()
 
        // 구글 로그인 옵션
        var gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id)) //토큰요청
            .requestEmail() //이메일 요청
            .build() //코드를 끝마치겠다
 
        // 구글 로그인 클래스를 만듬
        googleSignInClient = GoogleSignIn.getClient(this, gso) // 구글 로그인하는 클래스
        //callbackManager = CallbackManager.Factory.create() // 초기
 
        // 구글 로그인 버튼 이벤트
        google_sign_in_button.setOnClickListener { googleLogin() }
 
    }
 
 
    // 로그인 성공 시 이동할 페이지
    fun moveMainPage(user: FirebaseUser?) {
        if (user != null) {
            Toast.makeText(
                this,
                getString(R.string.signin_complete),
                Toast.LENGTH_SHORT
            ).show()
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
    }
 
    // 구글 로그인 코드
    fun googleLogin() {
        progress_bar.visibility = View.VISIBLE
        var signInIntent = googleSignInClient?.signInIntent
        startActivityForResult(signInIntent, GOOGLE_LOGIN_CODE)
    }
 
    // 구글 로그인 성공 했을 때 결과값이 넘어오는 함수
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
 
        // 구글에서 승인된 정보를 가지고 오기
        if (requestCode == GOOGLE_LOGIN_CODE) {
            val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
            if (result.isSuccess) {
                // 구글 로그인이 성공 했을 경우
                var account = result.signInAccount
                firebaseAuthWithGoogle(account!!)
               // moveMainPage(auth?.currentUser) //유저아이디를 넘겨준다.
            } else {
                progress_bar.visibility = View.GONE
            }
        }
    }
 
    // 구글 로그인 성공시 토큰값을 파이어베이스로 넘겨주어서 계정을 생성하는 콛,
    fun firebaseAuthWithGoogle(account: GoogleSignInAccount) {
        var credential = GoogleAuthProvider.getCredential(account.idToken, null)
        auth?.signInWithCredential(credential)
            ?.addOnCompleteListener { task ->
                progress_bar.visibility = View.GONE
                if (task.isSuccessful) {
                    //다음 페이지 호출
                    moveMainPage(auth?.currentUser)
                }
            }
    }
 
    // 자동 로그인 설정
    override fun onStart() {
        super.onStart()
        // 자동 로그인 설정
        moveMainPage(auth?.currentUser)
    }
 
}
 
cs



4. 어플을 실행하고 구글아이디로 로그인을 하면 MainActivity 화면으로 전환된다.



5. MainActivity 에 로그아웃버튼을 만들어서 로그아웃을 해보자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package kr.vrpano.wonstar
 
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_main.*
 
class MainActivity : AppCompatActivity() {
 
    // Firebase
    var auth: FirebaseAuth? = null
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        auth = FirebaseAuth.getInstance()
 
        //로그아웃 버튼 이벤트 처리
        account_btn_follow_signout.setOnClickListener { view ->
            auth?.signOut()
 
            startActivity(Intent(this, LoginActivity::class.java))
 
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package kr.vrpano.wonstar
 
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import kotlinx.android.synthetic.main.activity_login.*
 
class LoginActivity : AppCompatActivity() {
 
    // Firebase Authentication 관리 클래스
    var auth: FirebaseAuth? = null
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
 
        // Firebase Authentication 관리 클래스
        auth = FirebaseAuth.getInstance()
 
        // 이메일 로그인 이벤트 처리
        email_login_button.setOnClickListener { emailLogin() }
    }
 
    // 이메일 로그인 메소드
    fun emailLogin(){
        if (email_edittext.text.toString().isNullOrEmpty() ||
                password_edittext.text.toString().isNullOrEmpty()){
            Toast.makeText(this,getString(R.string.signout_fail_null),
                Toast.LENGTH_SHORT).show()
        } else {
            progress_bar.visibility = View.VISIBLE
            createAndLoginEmail()
        }
    }
 
    // 이메일 회원 가입 및 로그인 메소드
    fun createAndLoginEmail(){
 
        auth?.createUserWithEmailAndPassword(email_edittext.text.toString(),password_edittext.text.toString())?.addOnCompleteListener { task ->
                progress_bar.visibility = View.GONE
                if(task.isSuccessful){
                    moveMainPage(auth?.currentUser) //유저아이디를 넘겨준다.
                    Toast.makeText(this,getString(R.string.signup_complete),
                        Toast.LENGTH_SHORT).show()
                } else if (task.exception?.message.isNullOrEmpty()){
                    Toast.makeText(this,task.exception!!.message,Toast.LENGTH_SHORT).show()
                } else {
                    signinEmail()
                }
            }
    }
 
    // 로그인 메소드
    fun signinEmail(){
        auth?.signInWithEmailAndPassword(email_edittext.text.toString(),password_edittext.text.toString())
            ?.addOnCompleteListener{
                task -> progress_bar.visibility = View.GONE
 
                if (task.isSuccessful){
                    // 로그인 성공 및 다음 페이지 호출
                    moveMainPage(auth?.currentUser)
                } else {
                    // 로그인 실패
                    Toast.makeText(this,task.exception!!.message, Toast.LENGTH_SHORT).show()
                }
            }
    }
 
    // 로그인 성공 시 이동할 페이지
    fun moveMainPage(user : FirebaseUser?){
        if(user != null){
            Toast.makeText(this,
                getString(R.string.signin_complete),
                Toast.LENGTH_SHORT).show()
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
    }
}
 
cs


익명중첩클래스:

클래스나 인터페이스에 정의된 메서드를 Overriding하여 사용하고자 할 때 상속을 받은 클래스를 만들지 않고자 할 때 사용한다. 주로 메서드의 매개변수로 객체를 넘길 때 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
fun main(args : Array<String>){
    var t1 = TestClass2()
    method100(t1)
 
    var t2 = TestInter2()
    method200(t2)
    
}
 
// 추상클래스 정의
abstract class TestClass1{
 
    abstract fun test_method1()
 
}
 
// 인터페이스 정의
interface TestInter1{
    fun inter_method1()
}
 
// TestClass1의 test_method1메서드를 오버라이드한다.
class TestClass2 : TestClass1(){
    override fun test_method1() {
        println("TestClass2의 test_method1")
    }
}
 
// TestInter1의 inter_method1메서드를 오버라이드한다.
class TestInter2 : TestInter1{
    override fun inter_method1() {
        println("TestInter1의 inter_method1")
    }
 
}
 
// 추상클래스를 상속받은 메서드
fun method100(a1 : TestClass1){
    a1.test_method1()
}
 
// 인터페이스를 상속받은 메서
fun method200(a1 : TestInter1){
    a1.inter_method1()
}
cs



추상클래스나 인터페이스를 상속받은 메서드를 사용하려면 22~35번의 class를 만들어 줘야한다. 왜냐하면 추상클래스나 인터페이스는 객체를 생성할 수 없기 때문이다.

위처럼 class(22~35번줄) 작성하면 코드양도 많아지고 어렵다.

class를 사용하지 않을려면 아래처럼 작성하면 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
fun main(args : Array<String>){
 
    // 익명 중첩 클래스 사용
    method100(object : TestClass1(){
        override fun test_method1() {
            println("익명 중첩 클래스의 test_method1")
        }
    })
 
    // 익명 중첩 클래스 사용
    method200(object : TestInter1{
        override fun inter_method1() {
            println("익명 중첩 클래스의 test_inter1")
        }
 
    })
}
 
// 추상클래스 정의
abstract class TestClass1{
 
    abstract fun test_method1()
 
}
 
// 인터페이스 정의
interface TestInter1{
    fun inter_method1()
}
 
 
// 추상클래스를 상속받은 메서드
fun method100(a1 : TestClass1){
    a1.test_method1()
}
 
// 인터페이스를 상속받은 메서드
fun method200(a1 : TestInter1){
    a1.inter_method1()
}
 
cs


'코틀린' 카테고리의 다른 글

중첩클래스(내부클래스)  (0) 2018.11.26

@클래스안에 만드는 클래스를 중첩 클래스라고 한다

- 내부의 클래스는 외부의 클래스의 객체를 통해서만 객체를 생성할 수 있다.

- 외부의 클래스는 내부의 클래스 멤버를 사용할 수 없고 내부의 클래스는 외부의 클래스 멤버를 사용할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fun main(args : Array<String>){
    var a1 = Outer1()
    var a2 = a1.outer_member
    println(a2)
    var a3 = Outer1().inner1()
    var a4 = a3.inner_member
    println(a4)
}
 
class Outer1{
 
    var outer_member = 100
 
    inner class inner1{
        var inner_member = 200
 
        fun inner_method(){
            println(outer_member)
        }
    }
 
    fun outer_method(){
 
    }
}
cs


결과:

100

200

'코틀린' 카테고리의 다른 글

익명 중첩 클래스  (0) 2018.11.26

설명: 버튼을 클릭하면 id : textView 에 "버튼을 눌렀습니다." 메시지가 출력된다.


내부클래스(inner class) 를 이용한 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        var listener = BtnListener()
        click_Button.setOnClickListener(listener)
 
    }
 
    inner class BtnListener : View.OnClickListener{
        override fun onClick(v: View?) {
            textView.text = "버튼을 눌렀습니다."
        }
 
    }
}
cs


내부클래스(inner class) 를 이용해 여러버튼을 분기해서 사용하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
    var listener = BtnListener()
 
    button1.setOnClickListener(listener)
    button2.setOnClickListener(listener)
 
    }
 
    inner class BtnListener : View.OnClickListener{
        override fun onClick(v: View?) {
            when(v?.id){  //v객체에 버튼 주소값이 들어온다. id값을 가져온다.
                R.id.button1 ->
                    textView.text = "버튼1을 눌렀습니다."
                R.id.button2 ->
                    textView.text = "버튼2을 눌렀습니다."
            }
        }
    }
 
}
cs


================================================================================================================

람다식 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        click_Button.setOnClickListener { view ->
            textView.text = "버튼을 눌렀습니다."
        }
 
    }
 
}
cs


람다식을 사용하여 버튼을 분기할 때 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        var listener = View.OnClickListener{ view ->
            when(view.id){
                R.id.button1 ->
                    textView.text = "버튼1을 눌렀습니다."
                R.id.button2 ->
                    textView.text = "버튼2을 눌렀습니다."
            }
        }
 
       button1.setOnClickListener(listener)
       button2.setOnClickListener(listener)
    }
}
cs


1. 데이터 공유 설정 선택을 체크하고 완료버튼을 누른다.


2. 로그인 방법 설정을 클릭한다.


3. 오른쪽에 연필모양을 클릭한다.


4. 사용설정을 활성화 시켜주고 저장을 누른다.


5. 상태에 사용 설정됨이 라고 나온다.



+ Recent posts