티스토리 뷰


필요사항 :

- 구글 firebase 프로젝트 ( 서버키 )

- 구글 firebase 프로젝트 json 파일

- 노티를 받아주는 자바 서비스 코드

- 앱 내의 token 키

- 노티 날려줄 서버 





1. 구글 Firebase 


https://console.firebase.google.com/ 계정으로 접속


Firebase > 새 프로젝트 추가 > 프로젝트 관리 > JSON 파일 다운로드 


다운로드 받은 JSON 파일을 APP project 폴더에 추가


 


해당 프로젝트의 JSON 파일 다운로드 

 


다운로드한 JSON 파일을프로젝트/app 폴더에 추가


 







안드로이드 App 에 필요한 코드


APP 수준

compile 'com.google.firebase:firebase-messaging:9.6.1'
apply plugin:'com.google.gms.google-services'

Project 수준

dependencies {
classpath 'com.google.gms:google-services:3.0.0'

Manifast

<!-- [START firebase_service] -->
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>



MyFirebaseInstanceIDService.java


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
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = "MyFirebaseIIDService";
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
 
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]
 
    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }
}
 
cs



MyfirebaseMessagingService.java


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
 
public class MyFirebaseMessagingService extends FirebaseMessagingService {
   private static final String TAG = "MyFirebaseMsgService";
 
 
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
 
 
        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d(TAG, "From: " + remoteMessage.getFrom());
 
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }
 
        // Check if message contains a notification payload.
        // 앱이 켜져있을 때
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
 
    }
    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
 
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
 
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
 
}
 
cs


MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button btn = (Button) findViewById(R.id.btn);
 
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyFirebaseInstanceIDService service = new MyFirebaseInstanceIDService();
                service.onTokenRefresh();
            }
        });
    }
 
}
 
cs


버튼 클릭하여 실행 > 로그 확인 ( 토큰 복사 )




앱 실행 후 로그에 뜨는 Refreshed token: c0wtaoNTxV8:APA91bGev4hPxYHxJj.... <-- 앱 token



Firebase 콘솔에서 

OverView  > 프로젝트 관리 > 클라우드 메시징 > 서버키 복사


 







Node.js 로 서버 생성


테스트 로컬 서버 : http://localhost:8080/send_notification

serverUrl = https://fcm.googleapis.com/fcm/send (고정 구글 noti 주소)

serverKey = (복사한 서버키)


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
var express = require('express');
var fcm_push = require('fcm-push');
var body_parser = require('body-parser');
var app = express();
 
var serverKey = 'AAAA23VvuHk:APA9... 서버 키';
 
var fcm = new fcm_push(serverKey);
 
app.use(body_parser.urlencoded({
    extended:true
}));
 
app.post('/send_notification', function(req,res){
    var token         = req.body.noti_token; // noti_title = POST KEY 변수명
    var noti_title     = req.body.noti_title;
    var msg            = req.body.noti_msg;
 
    console.log(token+noti_title+msg);
 
    var jsonData = { to : token, 
                            notification : { 
                                title : noti_title,
                                body : msg
                            }
                        };
    fcm.send(jsonData, function(err, response){
        if(err){
            res.send('Fail:'+err);
        }else{
            res.send('Success:'+response.body);
        }
        
    });
    
});
 
app.listen(8080);
cs


서버 실행 ...




Postman POST 전송


app 로그에서 확인한 app token으로 전송


 



전송 결과 



'ANDROID > android' 카테고리의 다른 글

안드로이드 앱 진단[Drozer 사용법]  (0) 2017.05.25
Android ORM Lite  (0) 2017.02.18
Android - Alert 창 띄우기  (0) 2016.12.02
Android - phone 번호 가져오기  (0) 2016.11.30
Android - back 버튼 활용  (0) 2016.11.28
Comments
최근에 올라온 글
최근에 달린 댓글
TAG
more
Total
Today
Yesterday