google-services.json 파일을 다운받아서 프로젝트에 넣어준다

 

 

 

build.gradle.kts

plugins {
    ...
    
    // 파이어베이스
    id("com.google.gms.google-services") version "4.4.2"
}
 
 
dependencies {
    ...
 
    // 파이어베이스
    implementation(platform("com.google.firebase:firebase-bom:33.15.0"))
    implementation("com.google.firebase:firebase-analytics-ktx")
    implementation("com.google.firebase:firebase-messaging-ktx")
}
 
cs

 

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
 
    <!-- OS 13이상 -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
 
 
    <application>
        ...
 
        <!-- FCM 수신 서비스 -->
        <service android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
 
    </application>
 
</manifest>
cs

 

 

MainActivity.java

public class MainActivity extends AppCompatActivity {
 
    private final ActivityResultLauncher<String> permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
        if(isGranted) {
            requestPushToken();
        }
    });
 
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
 
        requestPermission();
    }
 
    // 알림수신 권한요청
    public void requestPermission() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
                return;
            }
        }
        requestPushToken();
    }
 
    // 푸시 토큰 가져오기
    public void requestPushToken() {
        FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
            @Override
            public void onComplete(@NonNull Task<String> task) {
                if(task.isSuccessful()) {
                    String token = task.getResult();
                    Log.d("PushToken", token);
                }
            }
        });
    }
}
cs

 

 

MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {
 
    private final String CHANNEL_ID = "PUSH_NOTI_CHANNEL";
    private final String CHANNEL_NAME = "푸시알림";
 
    // 새토큰 생성
    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);
        Log.d("PushToken", token);
    }
 
    // 푸시메시지 수신
    @Override
    public void onMessageReceived(@NonNull RemoteMessage message) {
        super.onMessageReceived(message);
        Log.d("Push""onMessageReceived");
 
        // 데이터
        Map<StringString> data = message.getData();
        String title = data.get("title");
        String content = data.get("content");
 
        // 알림띄우기
        createNotification(title, content);
    }
 
    public void createNotification(String title, String content) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            nm.createNotificationChannel(channel);
        }
 
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle(title);
        builder.setContentText(content);
        builder.setAutoCancel(true);
        builder.setNumber(1);
        builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
 
        if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
        manager.notify(1, builder.build());
    }
}
 
cs

 - 푸시메시지 수신하는 서비스

 

 

 

+ Recent posts