안드로이드2018. 12. 10. 16:09

파이어 베이스 가입 및 앱 추가 과정은 구글 검색하면 수도 없이 많아서 생략..귀찮은 건 안 비밀..

안드로이드 스튜디오에서 직접 하거나 아래 url에서 가입 및 세팅.

https://console.firebase.google.com/?hl=ko


기존 파이어베이스를 이용한 방식은 FirebaseInstanceIdService와 FirebaseMessagingService를 상속한

두 개의 클래스를 가지고 구현하였는데 현재는 FirebaseInstanceIdService가 deprecated되었다.


따라서 FirebaseMessagingService만을 활용하여 구현해보고자 한다.

프로젝트 단위 build.gradle에 다음을 추가한다.

buildscript {
  dependencies {
    ...
    classpath 'com.google.gms:google-services:4.0.1'
  }
}

앱 단위 build.gradle에 다음을 추가한다. 나의 경우 하단에 com.google.gms.google-services도 추가해야

정상적으로 구현이 되었다.

dependencies {
  ...
  implementation 'com.google.firebase:firebase-messaging:17.3.4'
  ...
}
apply plugin: 'com.google.gms.google-services'

주의할 것은 appli plugin: 'com.google.gms.google-services' 를 추가할 경우 play-services-ads를 사용하고 있다면

17.1.2 버전을 사용할 경우 오류가 발생한다. 따라서 버전을 17.1.1로 낮춰야 한다.

implementation 'com.google.android.gms:play-services-ads:17.1.1'

AndroidManifest.xml에도 추가해야 할 것이 있다.

<service
    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

이제 준비가 끝난 거 같다. 맞나? 


다음으로 FirebaseMessagingService를 상속받는 클래스를 만든다.

public class MyFirebaseMessagingService extends FirebaseMessagingService {
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    if(remoteMessage.getData() == null)
      return;
    sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("content"));
  }
 
  private void sendNotification(String title, String content) {
    if(title == null)
      title = "기본 제목";

    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtonManager.TYPE_NOTIFICATION);

    // 오레오(8.0) 이상일 경우 채널을 반드시 생성해야 한다.
    final String CHANNEL_ID = "채널ID";
    NotificationManager mManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      final String CHANNEL_NAME = "채널 이름";
      final String CHANNEL_DESCRIPTION = "채널 Description";
      final int importance = NotificationManager.IMPORTANCE_HIGH;

      // add in API level 26
      NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
      mChannel.setDescription(CHANNEL_DESCRIPTION);
      mChannel.enableLights(true);
      mChannel.enableVibration(true);
      mChannel.setVibrationPattern(new long[]{100, 200, 100, 200});
      mChannel.setSound(defaultSoundUri, null);
      mChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
      mManager.createNotificationChannel(mChannel);
    }
  
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
    builder.setAutoCancel(true);
    builder.setDefaults(Notification.DEFAULT_ALL);
    builder.setWhen(System.currentTimeMillis());
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setContentText(content);
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
      // 아래 설정은 오레오부터 deprecated 되면서 NotificationChannel에서 동일 기능을 하는 메소드를 사용.
      builder.setContentTitle(title);
      builder.setSound(defaultSoundUri);
      builder.setVibrate(new long[]{500, 500});
    }

    mManager.notify(0, builder.build());
  }

  @Override
  public void onNewToken(string s) {
    super.onNewToken(s);
    /* 
     * 기존의 FirebaseInstanceIdService에서 수행하던 토큰 생성, 갱신 등의 역할은 이제부터 
     * FirebaseMessaging에 새롭게 추가된 위 메소드를 사용하면 된다. 
     */
  }
}


이정도면 대충 정리가 되었으려나. 급하게 작성하느라 제대로 했는지 모르겠다.

까먹지 말자 좀 ... !



Posted by 홍규홍규