Browse Source

[푸시][New] 기본 작업

hyodong.min 6 years ago
parent
commit
452b814600

+ 6 - 14
app/src/main/AndroidManifest.xml

@@ -200,20 +200,12 @@
         android:resource="@xml/lifeplus_widget_info"/>
     </receiver>
 
-    <!-- 서비스 태그 추가 -->
-    <!--<service-->
-    <!--android:name=".MyFirebaseMessagingService">-->
-    <!--<intent-filter>-->
-    <!--<action android:name="com.google.firebase.MESSAGING_EVENT"/>-->
-    <!--</intent-filter>-->
-    <!--</service>-->
-
-    <!--<service-->
-    <!--android:name=".MyFirebaseInstanceIDService">-->
-    <!--<intent-filter>-->
-    <!--<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>-->
-    <!--</intent-filter>-->
-    <!--</service>-->
+    <service
+      android:name=".lifeplus.push.FirebasePushService">
+      <intent-filter>
+        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
+      </intent-filter>
+    </service>
   </application>
 
 </manifest>

+ 25 - 0
app/src/main/java/kr/co/zumo/app/lifeplus/activity/SplashActivity.java

@@ -7,6 +7,11 @@ import android.content.pm.PackageManager;
 import android.support.annotation.NonNull;
 import android.util.Log;
 
+import com.google.android.gms.tasks.OnCompleteListener;
+import com.google.android.gms.tasks.Task;
+import com.google.firebase.iid.FirebaseInstanceId;
+import com.google.firebase.iid.InstanceIdResult;
+
 import io.reactivex.android.schedulers.AndroidSchedulers;
 import io.reactivex.disposables.CompositeDisposable;
 import io.reactivex.schedulers.Schedulers;
@@ -44,6 +49,26 @@ public class SplashActivity extends ActivityBaseSetup {
     else {
       Log.e("APP#  SplashActivity | onCreate", "|" + " first ...........................");
 
+      // Get token
+      // [START retrieve_current_token]
+      FirebaseInstanceId.getInstance().getInstanceId()
+        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
+          @Override
+          public void onComplete(@NonNull Task<InstanceIdResult> task) {
+            if (!task.isSuccessful()) {
+              Log.e("APP#  SplashActivity | onComplete", "|" + "getInstanceId failed", task.getException());
+              return;
+            }
+
+            // Get new Instance ID token
+            String token = task.getResult().getToken();
+
+            // Log and toast
+            Log.d("APP# SplashActivity | onComplete", "|" + " token: " + token);
+          }
+        });
+      // [END retrieve_current_token]
+
       starter = new ScreenStarter(this);
 
       /*

+ 159 - 0
app/src/main/java/kr/co/zumo/app/lifeplus/push/FirebasePushService.java

@@ -0,0 +1,159 @@
+/*
+ * COPYRIGHT (c) 2018 All rights reserved by HANWHA LIFE.
+ */
+package kr.co.zumo.app.lifeplus.push;
+
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.BitmapFactory;
+import android.media.RingtoneManager;
+import android.net.Uri;
+import android.os.Build;
+import android.support.v4.app.NotificationCompat;
+import android.util.Log;
+
+import com.google.firebase.messaging.FirebaseMessagingService;
+import com.google.firebase.messaging.RemoteMessage;
+
+import java.util.Map;
+
+import kr.co.zumo.app.R;
+import kr.co.zumo.app.lifeplus.activity.MainActivity;
+import kr.co.zumo.app.lifeplus.model.SuperModel;
+
+
+/**
+ * FirebasePushService
+ * <pre>
+ * </pre>
+ *
+ * @author 민효동
+ * @version 1.0
+ * @history 민효동   [2019. 1. 30.]   [최초 작성]
+ * @since 2019. 1. 30.
+ */
+public class FirebasePushService extends FirebaseMessagingService {
+  private static final String TAG = FirebasePushService.class.getSimpleName();
+
+  /**
+   * 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.
+   */
+  @Override
+  public void onNewToken(String token) {
+    Log.d(TAG, "Refreshed token: " + token);
+
+    // If you want to send messages to this application instance or
+    // manage this apps subscriptions on the server side, send the
+    // Instance ID token to your app server.
+
+//    sendRegistrationToServer(token);
+  }
+
+  // 메시지 수신
+  @Override
+  public void onMessageReceived(RemoteMessage remoteMessage) {
+    Log.i(TAG, "onMessageReceived");
+
+    Log.i("APP# FirebasePushService | onMessageReceived", "|" + SuperModel.getInstance().getUserId());
+
+    // 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());
+
+      if (/* Check if data needs to be processed by long running job */ true) {
+        // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
+//        scheduleJob();
+      }
+      else {
+        // Handle message within 10 seconds
+//        handleNow();
+      }
+
+      Map<String, String> data = remoteMessage.getData();
+      String title = data.get("title");
+      String message = data.get("content");
+
+      Log.d("APP# FirebasePushService | onMessageReceived", "|" + " title: " + title + ", message: " + message);
+
+      sendNotification(title, message);
+    }
+
+    // Check if message contains a notification payload.
+    if (remoteMessage.getNotification() != null) {
+
+      String title = remoteMessage.getNotification().getTitle();
+      String message = remoteMessage.getNotification().getBody();
+      Log.d("APP# FirebasePushService | onMessageReceived", "| getNotification" + " title: " + title + ", message: " + message);
+
+      sendNotification(title, message);
+    }
+
+    // Also if you intend on generating your own notifications as a result of a received FCM
+    // message, here is where that should be initiated. See sendNotification method below.
+  }
+//  /**
+//   * Create and show a simple notification containing the received FCM message.
+//   *
+//   * @param messageBody FCM message body received.
+//   */
+  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(this, 0 /* Request code */, intent,
+      PendingIntent.FLAG_ONE_SHOT);
+
+    String channelId = "id";
+    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
+    NotificationCompat.Builder notificationBuilder =
+      new NotificationCompat.Builder(this, channelId)
+      .setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_dialog_info))
+        .setSmallIcon(R.mipmap.ic_launcher)
+        .setContentTitle(title)
+        .setContentText(messageBody)
+        .setAutoCancel(true)
+        .setSound(defaultSoundUri)
+        .setContentIntent(pendingIntent);
+
+    NotificationManager notificationManager =
+      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+
+    // Since android Oreo notification channel is needed.
+    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+      NotificationChannel channel = new NotificationChannel(channelId,
+        "Channel human readable title",
+        NotificationManager.IMPORTANCE_DEFAULT);
+      notificationManager.createNotificationChannel(channel);
+    }
+
+    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
+  }
+
+//  private void sendNotification(String title, String message) {
+//    Intent intent = new Intent(this, MainActivity.class);
+//    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+//    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
+//      PendingIntent.FLAG_CANCEL_CURRENT);
+//
+//    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
+//    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
+//      .setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_dialog_info))
+//      .setSmallIcon(R.mipmap.ic_launcher)
+//      .setContentTitle(title)
+//      .setContentText(message)
+//      .setAutoCancel(true)
+//      .setSound(defaultSoundUri)
+//      .setContentIntent(pendingIntent);
+//
+//    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+//    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
+//  }
+}