Android App

Notification with Python (FCM) in Android Studio

YunSeong 2021. 12. 21. 00:12
728x90
반응형

python을 이용해서 Firebase Cloud Messaging을 통해서 안드로이드 폰에 알람을 띄우는 것을 구현해봤다.

 

android에 firebase를 연결하는 거나 python의 모듈을 다운 받는 것은 생략한다.

1. FirebaseInstanceIDService.java (android part)

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
package com.example.smarttrashcanapplication;
 
import ...
 
public class FirebaseInstanceIDService extends FirebaseMessagingService {
 
    private static final String TAG = "FirebaseMsgService";
 
    private String msg, title;
 
    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        Log.d("NEW_TOKEN", s);
    }
 
    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        if (remoteMessage.getData()==null)
            return;
        sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("content"));
 
    }
 
    private void sendNotification(String title, String content) {
 
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        final String CHANNEL_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 = "채널 ";
            final int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
            mChannel.setDescription(CHANNEL_DESCRIPTION);
            mChannel.enableLights(true);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100200100200});
            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);
        builder.setContentText(title);
        builder.setSound(defaultSoundUri);
        builder.setVibrate(new long[]{500500});
        mManager.notify(0, builder.build());
    }
}
cs

위와 같이 FCM을 받고 그것을 바로 Notification을 띄워주는 것을 구현한다.


2. MainActivity.java (android part) (onCreate)

1
2
3
4
5
6
7
8
9
10
11
12
FirebaseMessaging.getInstance().getToken()
        .addOnCompleteListener(new OnCompleteListener<String>() {
            @Override
            public void onComplete(@NonNull Task<String> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                    return;
                }
                String token = task.getResult();
                Log.d(TAG, "token : "+token);
            }
        });
cs

위와 같은 코드를 통해서 token을 받아와야한다.


3. AndroidManifest.xml (android part)

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application
        ...
        <service android:name=".FirebaseInstanceIDService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>
cs

Manifest에 서비스를 등록해준다.


4. Python part

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from pyfcm import FCMNotification
 
APIKEY = "APIKEY"
TOKEN = "TOKEN"
push_service = FCMNotification(APIKEY)
 
def sendMessage(body, title):
    data_message = {
        "body":body,
        "title":title
        }
    result = push_service.single_device_data_message(registration_id=TOKEN, data_message=data_message)
    print(result)
 
 
#Execution area
sendMessage("알람 제목""알람 내용")
cs

위와 같은 코드를 통해서 TOKEN가 가리키는 기기에 알람을 보낸다.

728x90
반응형

'Android App' 카테고리의 다른 글

Room Database in Android Studio  (0) 2021.11.27
RecyclerView with Firebase in Android Studio  (0) 2021.11.27
Login with Firebase in Android Studio  (0) 2021.11.20
Kakao login in Android Studio  (0) 2021.11.12
Google login in Android Studio  (0) 2021.11.08