안드로이드

fcm push notification (firebase) 안드로이드 푸쉬알림 예제

소혜아빠 2017. 3. 3. 16:19

Firebase Cloud Messaging을 사용해서 안드로이드 푸시 알림을 구현하는 방법


1. project level의 build.gradle 파일에 google-service를 추가

dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
//classpath 'com.google.gms:google-services:3.0.0'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}

2. app level의 build.gradle 파일에 firebase-messaging을 추가하고 google-service plugin을 apply해준다.

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'

compile 'com.google.firebase:firebase-messaging:9.0.2'

}
apply plugin: 'com.google.gms.google-services'

3. Android-manifest.xml

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

태크 안에 위의 내용을 추가해 준다.


4. FirebaseInstanceIDService.java

/**
* Created by HKH on 2016-06-28.
*/
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";

// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String token = FirebaseInstanceId.getInstance().getToken();

}

}

사용자의 기기별 token을 생성하는 클래스이다.

여기서 token이란 나중에 push 알림을 특정 타겟에게 보낼 때 사용되는 고유 키 값이다.


5. FirebaseMessagingService.java


/**
* Created by HKH on 2016-06-28.
*/
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.RemoteMessage;

import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLConnection;


public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMsgService";

// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

sendPushNotification(remoteMessage.getData().get("message"));
}

private void sendPushNotification(String message) {
System.out.println("received message : " + message);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.noti).setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher) )
.setContentTitle("Push Title ")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri).setLights(000000255,500,2000)
.setContentIntent(pendingIntent);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakelock.acquire(5000);

notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}

푸쉬 메세지가 들어왔을 때 실제로 사용자가 푸쉬알림을 만들어서 띄워주는 클래스이다.

Api를 통해 푸쉬 알림을 전송하면 내용이 message에 담겨서 오게 된다.


6. MainActivity

import com.google.firebase.messaging.FirebaseMessaging;

onCreate 함수 안에

FirebaseMessaging.getInstance().subscribeToTopic("notice");

-> 여기서 topic은 api를 사용하여 푸시 알림 전송시 같은 토픽명 그룹 전체에 메세지를 발송 할 수 있음.

테스트는 Firebase Console의 Notification 메뉴에서 가능하다.