참고 : https://firebase.google.com/docs/android/setup?hl=ko
참고 : http://yamea-guide.tistory.com/226
6개월 간 진행한 프로젝트의 Android 개발 중 내 마지막 욕심은 Firebase 를 이용하여 Push서비스를 구현하는 것이었고, 해냈다.
구현하면서 느낀거지만 Firebase 는 정말 잘 만들었고, 누구나 쉽게 사용할 수 있도록 만들어준 것 같다.. 갓글bb
* 사용방법 *
1. 우선 Firebase 콘솔창에 들어가서 프로젝트를 하나 만들어준다. > https://console.firebase.google.com/?hl=ko
2. Firebase 도움말에 나와있는대로 Firebase와 연결시켜준다. > https://firebase.google.com/docs/android/setup?hl=ko#manually_add_firebase
=== 여기서부터는 Android Studio 설정 ===
3. AndroidManifest.xml 에 Firebase 사용을 위해 아래 코드를 추가해준다.
1 2 3 4 5 6 7 | <!-- Firebase Service --> <service android:name=".firebase.FirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> | cs |
4. Project Gradle 의 buildscript 안에 있는 dependencies 에 아래 한 줄 추가
1 2 | //Firebase & Google Map classpath 'com.google.gms:google-services:4.0.0' | cs |
5. App Gradle 상단에 아래 한 줄 추가
1 2 | apply plugin: 'com.google.gms.google-services' //Firebase | cs |
6. 그리고 dependencies 에 아래 한 줄 마저 추가
1 2 | //Firebase 사용을 위해 추가 implementation 'com.google.firebase:firebase-core:11.8.0' //16.0.0 | cs |
4. FirebaseInstanceIdService 를 상속받은 FirebaseInstanceIDService 클래스를 하나 생성해준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; public class FirebaseInstanceIDService extends FirebaseInstanceIdService { // InstanceID 토큰이 업데이트 되면 호출됨 // 이전 토큰의 보안이 손상된 경우에 발생할 수 있음 // InstanceID 토큰이 처음 생성될 때 호출되어 토큰을 검색하는 곳 @Override public void onTokenRefresh() { String refreshedToken = FirebaseInstanceId.getInstance().getToken(); System.out.println("========Refreshed token: " + refreshedToken); //SharedPreference.setAttribute(this,"firebase",refreshedToken); sendRegistrationToServer(refreshedToken); } // 3rd-party 서버에 토큰을 유지 // 이 메소드를 수정하여 사용자의 FCM 토큰을 서드파티에서 유지관리하는 서버측 계정과 연결 private void sendRegistrationToServer(String token) { //FCM 토큰 갱신 } } | 5.cs |
5. FirebaseMessagingService 를 상속받은 FirebaseMessagingService 클래스를 하나 생성해준다.
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 | import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.support.v4.app.NotificationCompat; import com.google.firebase.messaging.RemoteMessage; import com.nadri.MainActivity; import com.nadri.R; public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService { // 메세지를 받으면 호출 /* 데이터 메시지와 알림 메시지에는 두 가지 유형의 메시지가 있습니다. 1. 데이터 메시지는 앱이 포 그라운드인지 백그라운드인지에 관계없이 onMessageReceived 에서 처리됩니다. 데이터 메시지는 GCM에서 전통적으로 사용되는 유형입니다. 2. 알림 메시지는 앱이 포 그라운드에있을 때 onMessageReceived 에서만 수신됩니다. 앱이 백그라운드에있을 때 자동으로 생성 된 알림이 표시됩니다. 사용자가 알림을 탭하면 앱으로 돌아갑니다. 알림 및 데이터 페이로드가 모두 포함 된 메시지는 알림 메시지로 취급됩니다. Firebase 콘솔은 항상 알림 메시지를 전송합니다. 자세한 내용은 https://firebase.google.com/docs/cloud-messaging/concept-options를 참조하십시오. */ private String msg; // 수신한 FCM 메세지를 처리하는 메소드 @Override public void onMessageReceived(RemoteMessage remoteMessage) { System.out.println("===== From (어느놈이 보냈는지) : "+remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { System.out.println("===== Message data payload : "+remoteMessage.getData()); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { System.out.println("===== Message Notification Body (뭐라고 보냈는지) : "+remoteMessage.getNotification().getBody()); } msg = remoteMessage.getNotification().getBody(); //System.out.println("=====[END receive_message]====="); // 수신된 FCM 결과로 고유한 알림을 생성하려는 경우 Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) //알람을 받는 부분. 제목, 텍스트, 알림소리, 진동 횟수, 시간 등등 커스텀 가능! .setSmallIcon(R.mipmap.ic_launcher) //알림 좌측에 보여질 아이콘 .setContentTitle("알림도착~★") //알림에 보여질 큰 타이틀 .setContentText(msg) //알림에 보여질 작은 설명문구 .setAutoCancel(true) //알림 터치시 사라짐 .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) //알림 수신 소리 .setVibrate(new long[]{1, 1000}) //알림 수신 진동 .setWhen(System.currentTimeMillis()); //알림에 표시될 시간 NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, mBuilder.build()); mBuilder.setContentIntent(contentIntent); } } | cs |
그외.. 기기의 Token 을 받는 방법은 MainActivity 와 같은 곳에 아래 코드를 써주고 System.out.println 해주면 알 수 있다.
1 2 3 | //Firebase 토큰 받아오기 FirebaseInstanceId.getInstance().getToken(); String token = FirebaseInstanceId.getInstance().getToken(); | cs |
'MOBILE > Android' 카테고리의 다른 글
안드로이드 RollingText 사용법 (0) | 2018.08.08 |
---|---|
안드로이드 카카오 API 로그인 추가하기 (0) | 2018.08.07 |
안드로이드 위도,경도로 주소값 가져오는 방법 (0) | 2018.08.06 |
안드로이드 현재 내 위치값(좌표값) 구하기 (0) | 2018.08.05 |
안드로이드 Browser (Internet) 띄우기 (0) | 2018.08.03 |
댓글