코 틀린 push 알림 - ko teullin push allim

푸시알림(Push Notification) 기능이 필요해서 다시 만들어 보기로 했다. 몇번 만들어 봤지만 다시 만들어 보자. 먼저 새로운 안드로이드 스튜디오에서 코틀린으로 새로운 프로젝트를 생성한다.

코 틀린 push 알림 - ko teullin push allim
코 틀린 push 알림 - ko teullin push allim

메뉴에서 Tools > Firebase 선택하고 우측에서 Cloud Messaging / Set up ... 을 선택한다.

코 틀린 push 알림 - ko teullin push allim

이앱을 파이어베이스 프로젝트와 연결하는 작업이 필요하다. 콘솔에서 만들어 수동으로 연결하는 방법도 가능하다. 이게 편리하다. 새 프로젝트를 만들거나 기존의 프로젝트 중에 하나 선택한다.

코 틀린 push 알림 - ko teullin push allim

2번째 단계에서 Add FCM to your app을 클릭한다. 이러 이러한 업데이트가 이루어 진다는 설명문이 나온다. Accept Change 버튼을 클릭한다. gradle파일에서 의존성 라이브러리가 추가된 것을 확인 할 수 있다.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.js.kotlin_fcm_notification"> <uses-permission android:name="android.permission.INTERNET " /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--추가한 것--> <service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> </application> </manifest>

Manifests 를 열어서 activity 태그 아래 위와 같이 service 를 추가해 준다. 아직 빨간색으로 표시 된다. FCM으로 부터 메세지를 수진받고 기기로 알림을 보내는 클래스 파일을 저 빨간색과 동일한 이름으로 만들어 줘야 한다. 그리고 인터넷 퍼미션도 추가해 준다. 예전에는 FirebaseInstanceIdService라고 두번째 클래스 파일을 만들어서 사용했지만 지금은 이 FirebaseMessagingService 하나로 처리한다고 한다.

class MyFirebaseMessagingService: FirebaseMessagingService() { override fun onMessageReceived(remoteMessage: RemoteMessage?) { @SuppressLint("LongLogTAG")//이건 뭐지? if(remoteMessage?.notification != null){ sendNotification(remoteMessage.notification?.title, remoteMessage.notification!!.body!!) } } private fun sendNotification(title: String?, body: String){ //어떤 모양으로 알림을 할지 설정한 다음 실제 폰 상단에 표시하도록 한다. //pendingIntent를 이용 알림을 클릭하면 열 앱의 액티비티를 설정해 준다. val intent = Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT) val defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(title) .setContentText(body) .setSound(defaultSound) .setContentIntent(pendingIntent) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(0, notificationBuilder.build()) } }

수신된 알림이 있으면 이것을 기기에 표시하는 과정이다. 여기 까지 작성을 했으면 테스트를 해 볼 수 있다. 파이어베이스 콘솔에 접속해서 테스트 알림을 보내 보자. 앱을 설치한 폰에 알림이 도착하고 클릭하면 앱이 열리는 것을 확인 할 수 있다.

하지만 앱이 백그라운드 상태인지 실행되어 있는 상태인지에 따라 알림이 다르다. 실행된 상태일때는 알림 소리가 나지만 백그라운드 상태인 경우 소리는 나지 않고 알림만 표시된다. 이것에 대해서는 뒷부분에서 다시 알아 보기로 하자.

앱을 처음 시작하면 토큰이 자동으로 생성된다. 그후 토큰을 이용해서 단일 기기나 그룹에 알림을 보내는 등의 활용을 위해서 토큰을 앱서버에 저장해야 하는데 이럴때 아래 메소드를 이용하면 된다.

override fun onNewToken(token: String?) { super.onNewToken(token) Log.i(TAG, "Represhed token: " + token) //필요하면 이 토큰을 앱서버에 저장하는 과정을 거치면 된다. sendToken(token) }

토큰을 앱 서버에 저장한다. 추가 구현을 해야 한다. 구체적인 방법은 다음에 해보기로 하자.

아뭏든 이렇게 앱서버에 토큰이 저장되어 있으니 언제든지 꺼내서 활용이 가능해 진다.

class MainActivity : AppCompatActivity() { private val TAG = "MainActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //현재 기기의 토큰을 가져와서 출력 해보자. myToken() } private fun myToken() { //쓰레드 사용할것 Thread(Runnable { try { FirebaseInstanceId.getInstance().instanceId .addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.i(TAG, "getInstanceId failed", task.exception) return@OnCompleteListener } val token = task.result?.token textView.text = token //Log.d(TAG, token) }) } catch (e: IOException){ e.printStackTrace() } }).start() } }

MainActivity.kt 파일을 위와 같이 작성하자. 현재 기기의 토큰을 가져와서 메인페이지에 출력하는 코드이다.

코 틀린 push 알림 - ko teullin push allim
코 틀린 push 알림 - ko teullin push allim

파이어베이스 콘솔에서 테스트로 알림을 보내 보자. 그럼 위와 같은 결과가 나온다.

숙제:

- 앱이 백그라운드, 포그라운 일때의 알림

- 그외 OS8 이후에는 채널이라는 것을 도입했다는데 이건 다음에 알아 보기로 하자.

- 알림 클릭시 특정 액티비티 열기

- 알림 클릭시 특정 프래그먼트 열기

- PHP 웹페이지에서 알림 보내기

- 앱에서 알림 보내기(http요청)

다음편에 계속...