Code

Code

วันอาทิตย์ที่ 12 มิถุนายน พ.ศ. 2559

ANDROID : Firebase Cloud Messaging Tutorial ( step by step : ภาษาไทย)

    เนื่องจาก  GCM Cloud Messaging ตัวเดิมของ Google นั้นหยุดพัฒนาและได้ให้นักพัฒนาหันมาใช้ Cloud Messaging ตัวใหม่แทน มีชื่อว่า Firebase Cloud Messaging (FCM) โดยโครงสร้างพื้นฐายส่วนใหญ่ถูกพัฒนาขึ้นมาจาก ​GCM ตัวเดิมนั้นเอง ซึ่งหากเราเข้าไปหน้าเว็บของ GCM จะมีข้อความขึ้นเตือนให้หันมาใช้ Firebase แทน


ในเมื่อเขาบอกให้เปลี่ยน เราเป็นนักพัฒนาก็ต้องพัฒนาตัวเองตามเทคโนโลยีไปด้วย เรามาลองดู Firebase กันเถอะ    https://firebase.google.com/

พอหลังจากเข้ามาหน้าเว็บเราก็จะเห็น 6 tab ใหญ่ๆ ได้แก่
-  Home  อธิบายภาพรวมต่างๆของ Firebase
- Features หัวข้อบริการต่างๆของ Firebase
- Pricing ราคาค่าบริการ ซึ่ง Cloud Messaging ที่เราจะใช้งานนั้น ฟรี  //เย้ๆๆ
- Docs คู่มือสำหรับนักพัฒนาอย่างเราๆนั้นเอง
- Customers รายชื่อลูกค้าที่มาใช้บริการของ Firebase
- Support เป็นการช่วยเหลือนักพัฒนาหรือลูกค้า ซึ่งในหน้านี้มีการบอกว่า Firebase status : Firebase สมบูรณ์แบบ!   มั่นใจได้ว่าไม่ใช่ตัว Demo หรือกำลังพัฒนาแล้วนะ แต่มันสามารถนำไปใช้งานได้แล้วนั้นเอง 


สิ่งหนึ่งที่เป็นจุดเด่นของ Firebase Cloud Messaging (FCM) ก็คือ FCM มีหน้า console ให้เราสามารถ push message ไปยัง device ได้โดยตรงเลย // เย้ๆ















เข้าเนื้อหากันเลย !!
เริ่มจาก Setup กันก่อน ตัว Firebase Cloud Messaging (FCM) นั้นต้องใช้กับ Android studio 1.4 ขึ้นไปและทำงานร่วมกับ Gradle หากพร้อมแล้วก็ไปต่อกัน

- Create New Project บน Firebase Console


- เลือก Country/region : Thailand


- Add Firebase

- กรอก Pacekage name ของ แอพเรา และ ตามด้วย SHA-1

(วิธีหา package name และ SHA-1 "debug.keystore")

- โหลด google-services.json ไปไว้ในโฟลเดอร์ app ของโปรเจคเรา
- เพิ่มคำสั่งใน build.gradle 
buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:3.0.0'
    }
}
 - เพิ่มคำสั่งใน build.gradle  (Module:app)
apply plugin: 'com.android.application'

android {
  // ...
}

dependencies {
  // ...
  compile 'com.google.firebase:firebase-messaging:9.0.2'}
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'
- create class "MyFirebaseMessagingService"

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO(developer): Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // 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.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }
    // [END receive_message]

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(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);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(android.R.drawable.ic_dialog_alert)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}
อธิบาย : เมธอด onMessageReceived() ทำหน้าที่รับข้อความที่ทาง server ส่งมาให้ ส่วน sendNotification() นั้นสำหรับแสดง Notification ซึ่งตรงๆจุดๆนี้ คือสิ่งที่แตกต่างจาก GCM เดิม เพราะ FirebaseMessagingService ในโค้ดด้านบนนี้จะทำงานเฉพาะ foreground (ขณะที่แอพเปิดอยู่) เท่านั้น ซึ่งถ้าแอพทำงานเบื้องหลังหรือไม่ได้เปิดแอพอยู่แล้วมี Notification เข้ามา หากคลิกดูจะไปเปิดแอพเท่านั้น โค้ดที่เราเซตไว้ใน MyFirebaseMessagingService จะไม่ทำงาน(intent ไปหน้าอื่น , เสียง ,Title , icon , ...) ซึ่งผมจะไปอธิบายใน Part-2 ละกัน หลักๆคือต้องส่งค่าผ่าน Firebase Console หรือบน Server นั้นเอง

- และ create class "MyFirebaseInstanceIDService"
public class MyFirebaseInstanceIDService 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() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        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) {
        // Add custom implementation, as needed.
    }
}
อธิบาย : คลาสนี้ทำหน้าที่ในการรับค่า Token เพื่อเอาไว้ใช้สำหรับให้ Server push notification มาได้ ซึ่งตัวอย่างที่เราทำนี้ ไม่ได้ส่ง Token ไปยัง Server ที่ไหน เลยไม่ได้เรียกใช้เมธอด onTokenRefresh() 

ประกาศ service class ทั้ง 2 ใน  AndroidManifest.xml
<!-- [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>
<!-- [END firebase_iid_service] -->

- ทดสอบ run app ได้เลย แล้วไปหน้า Firebase console  เราจะมาลองทดสอบส่ง push notification มายังเครื่องที่ run app


- Message Text : พิมข้อความที่ต้องการส่ง
- Target : เลือก Package Name หรือจะส่งไปแค่เครื่องเดียวโดยเลือก Single device แล้วกรอก token ของเครื่องเป้าหมาย
- Advance options : Priority = high , Sound = Enabled

คลิก SEND MESSAGE โลดดดดดด

รอประมาณไม่เกิน 5 วินาที  Notification จะเข้า
มาแล้วววว !!!!!

หากไม่เข้า ให้ทำดังนี้นะครับ จุดธูปสามดอกแล้วพนมมือ... #ผิด จริงๆแล้วต้องธูปเก้าดอก #ผิด ให้ลองย้อนกลับไปดูตั้งแต่แรกว่าพลาดตรงไหนหรือเปล่า 

gl hf ggwp.


Download : SourceCode

Reference 




ไม่มีความคิดเห็น :

แสดงความคิดเห็น