반응형
- 필요한 기술
1. 리사이클 뷰.
2. google fcm push서버에 http통신.
3. firebase realtimeDB 쿼리문 가저오기.
4. background 상태 확인.
DB구성
- ChatList: 사용자간에 채팅 기록을 저장.
- receiver와 sender로 사용자를 구분함.
- fcmToken: 해당유저의 현재 fcm토큰을 저장.
1. 리사이클 뷰.
2. google fcm push서버에 http통신.
1.기존
firebase.google.com/docs/cloud-messaging/http-server-ref?hl=ko
Request
- url: https://fcm.googleapis.com/fcm/send
- type: post
Header
{
"Content-Type:application/json",
"Authorization:key=YOUR_FCM_SERVER_KEY"
}
Body
{
"to":"your-send-firebasekey"
,"data":{
"title":"1234",
"body":"asd",
"key_1":"1234",
"key_2":"1234"
}
}
-
data object 안쪽 데이터 구성은 원하는 데이터로 구성하면 된다.
Response
{
"multicast_id": 123456781234,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:129831yh2-eubsd9fh23093j234"
}
]
}
2. 새버전
firebase.google.com/docs/cloud-messaging/migrate-v1?hl=ko
- 새버전은 google api 라이브러리를 받아서 써야한다.
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.30.10</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
- fcm 서버로 부터 인증토큰을 받아온다.
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("YOUR_JSON_FILE_LOCATION"))
.createScoped(Arrays.asList(SCOPES));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
- 받은 토큰을 header key 중 Authorization의 값으로 사용한다.
private static HttpURLConnection getConnection() throws IOException {
// [START use_access_token]
URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
return httpURLConnection;
// [END use_access_token]
}
- 위에서 setting한 데이터로 통신을 보낸다.
/**
* Send request to FCM message using HTTP.
*
* @param fcmMessage Body of the HTTP request.
* @throws IOException
*/
private static void sendMessage(JsonObject fcmMessage) throws IOException {
HttpURLConnection connection = getConnection();
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(fcmMessage.toString());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
String response = inputstreamToString(connection.getInputStream());
System.out.println("Message sent to Firebase for delivery, response:");
System.out.println("responseCode: "+responseCode);
System.out.println(response);
} else {
System.out.println("Unable to send message to Firebase:");
String response = inputstreamToString(connection.getErrorStream());
System.out.println("responseCode: "+responseCode);
System.out.println(response);
}
}
Request
{
"message": {
"notification": {
"title": "FCM Notification",
"body": "Notification from FCM"
},
"token": "YOUR_DEVICE_FCM_TOKEN"
}
}
-
notification 값은 별도의 FirebaseMessagingService.class 구현없이도 알림이 가능하다.
Response
{
"name": "projects/YOUR_PROJECT_ID/messages/0:1610703319299158%f3fd72f7f3fd72f7"
}
3. firebase realtimeDB 쿼리문 가저오기.
firebase.google.com/docs/database/android/start?hl=ko
4. background 상태 확인.
구현
public class CustomApplication extends Application implements Application.ActivityLifecycleCallbacks {
public static boolean isBackground = true;
private static int numStarted = 0;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks( this );
}
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) { }
@Override
public void onActivityStarted(@NonNull Activity activity) {
if (numStarted == 0) {
// app went to foreground
isBackground = false;
}
numStarted++;
}
@Override
public void onActivityResumed(@NonNull Activity activity) { }
@Override
public void onActivityPaused(@NonNull Activity activity) { }
@Override
public void onActivityStopped(@NonNull Activity activity) {
numStarted--;
if (numStarted == 0) {
// app went to background
isBackground = true;
}
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) { }
@Override
public void onActivityDestroyed(@NonNull Activity activity) { }
}
- - isBackground로 구분 가능.
반응형
'AOS' 카테고리의 다른 글
(Android) 트위치 App 3 - retrofit2 (0) | 2021.04.19 |
---|---|
(Android) 트위치 app 2 - ANR WatchDog (0) | 2021.04.16 |
(안드로이드) jobService (0) | 2020.10.15 |
(안드로이드) 인앱결제(billingClient v3) (0) | 2020.10.08 |
(android)pinch zoom imageview (0) | 2020.09.03 |