관리 메뉴

나만을 위한 블로그

[Android] FCM 푸시 알람 보내는 서비스 파일 코드 본문

Android

[Android] FCM 푸시 알람 보내는 서비스 파일 코드

참깨빵위에참깨빵_ 2020. 5. 26. 11:18
728x90
반응형

아래 클래스들을 만든 후 매니페스트의 <activity> 태그 바로 아래에 <service> 태그 만들어야 함

 

// MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FCM";

    private static int count = 0;

    @Override
    public void onNewToken(@NonNull String s)
    {
        super.onNewToken(s);
        Log.e(TAG, "onNewToken() : " + s);
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage)
    {
        try {
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendNotification(String title, String messageBody)
    {
        Intent intent = new Intent(getApplicationContext(), ChatRoomInviteActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("pushnotification", "yes");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // For Android Version Orio and greater than orio.
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel mChannel = new NotificationChannel("Sesame", "Sesame", importance);
            mChannel.setDescription(messageBody);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

            mNotifyManager.createNotificationChannel(mChannel);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "Seasame");
            mBuilder.setContentTitle(title)
                    .setContentText(messageBody)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setColor(Color.parseColor("#FFD600"))
                    .setContentIntent(pendingIntent)
                    .setChannelId("Sesame")
                    .setPriority(NotificationCompat.PRIORITY_LOW);

            mNotifyManager.notify(count, mBuilder.build());
            count++;
        }
    }
}
// MyFirebaseMessagingIDService.java

public class MyFirebaseMessagingIDService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebase";

    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token){
        //기타 작업으로 활용

    }

}
<service
            android:name="com.패키지명.패키지명.FCM.MyFirebaseMessagingIDService"
            android:stopWithTask="false">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        
        <service
            android:name="com.패키지명.패키지명.FCM.MyFirebaseMessagingService"
            android:stopWithTask="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

 

이렇게 작성 후 포스트맨에서 아래처럼 작성함

Authorization 우측에는 서버 키를 넣어줘야 한다. 밸류값에 "key=서버키" 형식으로 넣어줘야 함

 

헤더를 위와 같이 작성하고 바로 옆의 Body를 눌러 아래처럼 작성함

 

반응형
Comments