FCM Firebase Cloud Messaging 1 Firebase v Firebase
FCM (Firebase Cloud Messaging) 1
Firebase v Firebase 설정: https: //console. firebase. google. com 에 접속해서 로그인 ü 프로젝트 추가 3
Firebase v Firebase 설정 ü 프로젝트 추가 4
Firebase v Firebase 설정 ü 프로젝트 추가 5
Firebase v Firebase 설정 ü 프로젝트 추가 6
Firebase v Firebase 설정 ü 프로젝트 나 모듈 생성 – kakao. itstudy. fcm ü Firebase Overview 화면에서 Android 앱에 Firebase 추가 클릭 7
Firebase v Firebase 설정 ü Android 앱 정보 입력 9
Firebase v Firebase 설정 ü Android 앱 정보 입력 10
Firebase v Firebase 설정 ü 프로젝트 수준의 build. gradle 파일에 추가 // Top-level build file where you can add configuration options common to all subprojects/modules. buildscript { ext. kotlin_version = '1. 4. 20 -RC' ext. kotlin_version = "1. 3. 72" repositories { google() jcenter() } dependencies { classpath "com. android. tools. build: gradle: 4. 1. 0" classpath "org. jetbrains. kotlin: kotlin-gradle-plugin: $kotlin_version" } } // NOTE: Do not place your application dependencies here; they belong // in the individual module build. gradle files classpath 'com. google. gms: google-services: 4. 3. 4' 11
Firebase v Firebase 설정 ü 모듈 수준의 build. gradle 파일에 추가 plugins { id 'com. android. application' id 'kotlin-android-extensions' id 'com. google. gms. google-services' } dependencies { implementation platform('com. google. firebase: firebase-bom: 26. 0. 0') implementation 'com. google. firebase: firebase-analytics-ktx' implementation "org. jetbrains. kotlin: kotlin-stdlib: $kotlin_version" implementation 'androidx. core: core-ktx: 1. 3. 2' implementation 'androidx. appcompat: 1. 2. 0' implementation 'com. google. android. material: 1. 2. 1' implementation 'androidx. constraintlayout: 2. 0. 4' test. Implementation 'junit: 4. +' android. Test. Implementation 'androidx. test. ext: junit: 1. 1. 2' android. Test. Implementation 'androidx. test. espresso: espresso-core: 3. 3. 0' } 12
Firebase v Firebase 설정 확인 ü 콘솔 화면에서 Realtime Database 선택 13
Firebase v Firebase 설정 확인 ü 앱의 Main. Acticity. kt 파일에 작성하고 실행 16
Firebase v Firebase 설정 확인 ü 앱의 Main. Acticity. kt 파일에 작성하고 실행 class Main. Activity : App. Compat. Activity() { // 로그에 TAG 로 사용할 문자열 val TAG = "Main. Activity" // 파이어베이스의 test 키를 가진 데이터의 참조 객체를 가져온다. val ref = Firebase. Database. get. Instance(). get. Reference("nickname") 17
Firebase v Firebase 읽기 ü 앱의 Main. Acticity. kt 파일에 작성하고 실행 override fun on. Create(saved. Instance. State: Bundle? ) { super. on. Create(saved. Instance. State) set. Content. View(R. layout. activity_main) // 값의 변경이 있는 경우의 이벤트 리스너를 추가한다. ref. add. Value. Event. Listener(object : Value. Event. Listener { // 데이터 읽기가 취소된 경우 호출 된다. // ex) 데이터의 권한이 없는 경우 override fun on. Cancelled(error: Database. Error) { error. to. Exception(). print. Stack. Trace() } // 데이터의 변경이 감지 되면 호출된다. override fun on. Data. Change(snapshot: Data. Snapshot) { // nickname 키를 가진 데이터 스냅샷에서 값을 읽고 문자열로 변경한다. val message = snapshot. value. to. String() Toast. make. Text(this@Main. Activity, message, Toast. LENGTH_LONG). show() // Firebase 에서 전달받은 메세지로 제목을 변경한다. support. Action. Bar? . title = message } }) } } 18
Firebase v Firebase 기록 ü 새로운 클래스 생성 class Post { var post. Id = "" var writer. Id = "" var message = "" var write. Time: Any = Any() var comment. Count = 0 } 19
Firebase v Firebase 기록하기 ü 앱의 Main. Acticity. kt 파일에 작성하고 실행 override fun on. Create(saved. Instance. State: Bundle? ) { super. on. Create(saved. Instance. State) set. Content. View(R. layout. activity_main) // Post 객체 생성 val post = Post() // Firebase 의 Posts 참조에서 객체를 저장하기 위한 새로운 카를 생성하고 참조를 new. Ref 에 저장 val new. Ref = Firebase. Database. get. Instance(). get. Reference("Posts"). push() // 글이 쓰여진 시간은 Firebase 서버의 시간으로 설정 post. write. Time = Server. Value. TIMESTAMP // 메세지는 input Edit. Text 의 텍스트 내용을 할당 post. message = "안녕하세요 첫번째 글입니다. " // 글쓴 사람의 ID 는 디바이스의 아이디로 할당 post. writer. Id = Settings. Secure. get. String(this. content. Resolver, Settings. Secure. ANDROID_ID) // 글의 ID 는 새로 생성된 파이어베이스 참조의 키로 할당 post. Id = new. Ref. key. to. String() // Post 객체를 새로 생성한 참조에 저장 new. Ref. set. Value(post) // 저장성공 토스트 알림을 보여주고 Activity 종료 Toast. make. Text(application. Context, "공유되었습니다. ", Toast. LENGTH_SHORT). show() } } 20
Firebase v Firebase 기록하기 21
Firebase v Firebase 삭제 val ref = Firebase. Database. get. Instance(). get. Reference("nickname") ref. remove. Value() 22
Firebase v Firebase 수정 val ref = Firebase. Database. get. Instance(). get. Reference() val child. Updates: Mutable. Map<String, Any> = mutable. Map. Of() val user. Value: Mutable. Map<String, Any> = mutable. Map. Of() user. Value. put("message", "데이터를 수정합니다. ") child. Updates. put("/Posts/" + "-MLld 5 j. ILz 4 i 1 KMNszm. Y", user. Value); ref. update. Children(child. Updates); Toast. make. Text(application. Context, "수정 성공. ", Toast. LENGTH_SHORT). show() 23
FCM 25
FCM 설정 v build. gradle 파일에 의존성 설정 dependencies { implementation platform('com. google. firebase: firebase-bom: 26. 0. 0') implementation 'com. google. firebase: firebase-analytics-ktx' implementation 'com. google. firebase: firebase-messaging-ktx' implementation "org. jetbrains. kotlin: kotlin-stdlib: $kotlin_version" implementation 'androidx. core: core-ktx: 1. 3. 2' implementation 'androidx. appcompat: 1. 2. 0' implementation 'com. google. android. material: 1. 2. 1' implementation 'androidx. constraintlayout: 2. 0. 4' implementation 'com. google. firebase: firebase-database-ktx: 19. 5. 1' test. Implementation 'junit: 4. +' android. Test. Implementation 'androidx. test. ext: junit: 1. 1. 2' android. Test. Implementation 'androidx. test. espresso: espresso-core: 3. 3. 0' } 27
FCM 설정 v FCM 메시지 수신을 위한 클래스 생성 - My. Firebase. Messaging. Service class My. Firebase. Messaging. Service : Firebase. Messaging. Service() { // FCM 에서 메세지가 온경우 호출됨 override fun on. Message. Received(remote. Message: Remote. Message) { // Check if message contains a notification payload. remote. Message? . notification? . let { Log. d(TAG, "Message Notification Body: ${it. body}") send. Notification(it. body ? : "message") } } // 새로운 토큰이 발행될때 - 토큰은 특정 기기에 푸쉬메세지를 보낼때 사용할 수 있음 override fun on. New. Token(token: String) { Log. d(TAG, "Refreshed token: $token") send. Registration. To. Server(token) } // 유저의 FCM 토큰을 서버에 등록해야 한다면 이 함수에서 코드를 작성 private fun send. Registration. To. Server(token: String? ) { // 서버에 토큰정보를 전송하는 코드 작성 필요 } 28
FCM 설정 v FCM 메시지 수신을 위한 클래스 생성 - My. Firebase. Messaging. Service // FCM 메세지를 기반으로 알림 메세지 보여줌 private fun send. Notification(message. Body: String) { val intent = Intent(this, Main. Activity: : class. java) intent. add. Flags(Intent. FLAG_ACTIVITY_CLEAR_TOP) val pending. Intent = Pending. Intent. get. Activity(this, 0 /* Request code */, intent, Pending. Intent. FLAG_ONE_SHOT) val channel. Id = "News" val default. Sound. Uri = Ringtone. Manager. get. Default. Uri(Ringtone. Manager. TYPE_NOTIFICATION) val notification. Builder = Notification. Compat. Builder(this, channel. Id). set. Small. Icon(R. mipmap. ic_launcher_round). set. Content. Title("FCM 메세지"). set. Content. Text(message. Body). set. Auto. Cancel(true). set. Sound(default. Sound. Uri). set. Content. Intent(pending. Intent) 29
FCM 설정 v FCM 메시지 수신을 위한 클래스 생성 - My. Firebase. Messaging. Service val notification. Manager = get. System. Service(Context. NOTIFICATION_SERVICE) as Notification. Manager // Since android Oreo notification channel is needed. if (Build. VERSION. SDK_INT >= Build. VERSION_CODES. O) { val channel = Notification. Channel(channel. Id, "Channel human readable title", Notification. Manager. IMPORTANCE_DEFAULT) notification. Manager. create. Notification. Channel(channel) } notification. Manager. notify(0 /* ID of notification */, notification. Builder. build()) } companion object { private const val TAG = "My. Firebase. Msg. Service" } } 30
FCM 설정 v FCM 메시지 수신을 위한 클래스 생성 - My. Firebase. Messaging. Service val notification. Manager = get. System. Service(Context. NOTIFICATION_SERVICE) as Notification. Manager // Since android Oreo notification channel is needed. if (Build. VERSION. SDK_INT >= Build. VERSION_CODES. O) { val channel = Notification. Channel(channel. Id, "Channel human readable title", Notification. Manager. IMPORTANCE_DEFAULT) notification. Manager. create. Notification. Channel(channel) } notification. Manager. notify(0 /* ID of notification */, notification. Builder. build()) } companion object { private const val TAG = "My. Firebase. Msg. Service" } } 31
FCM 설정 v FCM 메시지 수신을 서비스 설정 – Android. Manifest. xml <service android: name=". My. Firebase. Messaging. Service" android: enabled="true" android: exported="true"> <intent-filter> <action android: name="com. google. firebase. MESSAGING_EVENT" /> </intent-filter> </service> 32
FCM 설정 v Firebase 콘솔에서 Cloud Messaging 클릭 33
개발자 계정 등록 v 계정 등록 ü https: //play. google. com/console/signup 40
스토어 등록정보 설정 v Google Play Console 에 접속: https: //play. google. com/console/ 49
- Slides: 64