FCM 앱 알람

Posted by PeEn
2019. 11. 2. 23:12 Programing/Android

1. FCM 프로젝트 생성

2.안드로이드 아이콘 클릭하여 앱 등록과정 진행

3.패키지명 입력, 앱이름(아무거나)입력 후 앱등록 ->
구성파일 다운로드 google-services-json 파일 다운로드 후
안드로이드 스튜디오 작업 프로젝트로 가서 Android보기에서 Project보기로 변경 후 app디렉터리에 파일을 넣는다
그리고 다음버튼 ->
build에 넣으라는 것들 넣고 sync now 클릭해서 적용 후 다음

4.안드로이드 스튜디오 Tools -> Firebase 클릭 Cloud Messaging 클릭  Set up Firebase Cloud Messaging 클릭

 Connect your app to Firebase 클릭

5. manifests 클릭 후 </application>이전에 삽입

  <service
            android:name=".Service.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name=".Service.MyFirebaseInstanceservice">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

6. 패키지 디렉터리에 Service라는 패키지(디렉터리) 생성
Service 디렉터리 안에 MyFirebaseInstanceservice.java 생성 후 아래 코드 삽입

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class MyFirebaseInstanceservice extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // 설치할때 여기서 토큰을 자동으로 만들어 준다
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // 생성한 토큰을 서버로 날려서 저장하기 위해서 만든거
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.

        // OKHTTP를 이용해 웹서버로 토큰값을 날려준다.
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token", token)
                .build();

        //request
        Request request = new Request.Builder()
                .url("http://db와php있는서버주소/resigster.php")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

* .url("http://db와php있는서버주소/resigster.php")

에서 'db와php있는서버주소' 부분을 자신의 서버주소로 변경!

6. 오른쪽 Firebase창에서 Add FCM to your app에 버튼 클릭해서 Firebase 적용
(오른쪽에 Firebase창이 없으면 안드로이드 스튜디오 Tools -> Firebase 클릭 Cloud Messaging 클릭  Set up Firebase Cloud Messaging 클릭)

7. Service 디렉터리에 MyFirebaseMessagingService.java 생성 후 아래 코드 삽입

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;

import androidx.core.app.NotificationCompat;

import com.debtorlee.projectuniv.Main_ShowData;
import com.debtorlee.projectuniv.R;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends  com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMsgService";

// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

        //추가한것
        sendNotification(remoteMessage.getData().get("message"));
        }

private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, Main_ShowData.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
        PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("FCM Push Test") // 이부분은 어플 켜놓은 상태에서 알림 메세지 받으면 저 텍스트로 띄워준다.
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
        }

        }



8. 처음시작되는 java에 다음 소스 추가

public class MainActivity extends AppCompatActivity {
.
.
.
.
  @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showdata);

        //추가한 라인
        FirebaseApp.initializeApp(this);
        FirebaseMessaging.getInstance().subscribeToTopic("news");
        FirebaseInstanceId.getInstance().getToken();
        
    }
.
.
.

9. config.php와 resigster.php 파일을 만들어 수정 후 html서버에 저장하여 호스팅한다.

resigster.php 안의 내용을 자신의 정보에 맞게 작성하고 저장하는 것 유의~!

*config.php

<?php
	define("DB_HOST", "localhost");
	define("DB_USER", "MYSQL DB ID");
	define("DB_PASSWORD", "MYSQL DB 비밀번호");
	define("DB_NAME", "fcm");

	define("GOOGLE_API_KEY", "FCM 프로젝트 서버키"); 

?>

*resigster.php

<?php

	if(isset($_POST["Token"])){

		$token = $_POST["Token"];
		//데이터베이스에 접속해서 토큰을 저장
		include_once 'config.php';
		$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
		$query = "INSERT INTO users(Token) Values ('$token') ON DUPLICATE KEY UPDATE Token = '$token'; ";
		mysqli_query($conn, $query);

		mysqli_close($conn);
	}
?>

10. 실행 후 DB에 토큰 key가 들어오는지 확인하여 작동하는지 확인한다.


파이썬 서버

import http.client
import pymysql

import requests
import json


#def send_fcm_notification(ids, title, body):
def send_fcm_notification(ids, title, body):
    # fcm 푸시 메세지 요청 주소
    url = 'https://fcm.googleapis.com/fcm/send'
    
    # 인증 정보(서버 키)를 헤더에 담아 전달
    headers = {
        'Authorization': 'key= 서버키',
        'Content-Type': 'application/json; UTF-8',
    }

    # 보낼 내용과 대상을 지정
    content = {
        'registration_ids': ids,
        'notification': {
            'title': title,
            'body': body
        }
    }

    # json 파싱 후 requests 모듈로 FCM 서버에 요청
    requests.post(url, data=json.dumps(content), headers=headers)



# MySQL Connection 연결

connection = pymysql.connect(host="localhost", port=3306, user="아이디", password="비밀번호",
					  db='fcm', charset='utf8')


try:
    with connection.cursor() as cursor:  
        sql = "select Token from users"
        cursor.execute(sql)
        result = cursor.fetchall()
        
        for i in result:
            send_fcm_notification(i,"제목","내용")
            
                  
finally:
    connection.close()


connection.close()