Firebase系列之---Cloud Messaging/Notifications(云消息,推送)的使用

轉(zhuǎn)載請(qǐng)注明出處:http://www.lxweimin.com/p/3b880a09f754
本文出自Shawpoo的簡(jiǎn)書
我的博客:CSDN博客

1、Firebase系列之---初探Firebase

2、Firebase系列之---Cloud Messaging/Notifications(云消息,推送)的使用

3、Firebase系列之—Realtime Database(實(shí)時(shí)數(shù)據(jù)庫(kù))的使用

Cloud Messaging

Firebase Cloud Messaging (FCM) 是一種跨平臺(tái)消息傳遞解決方案,開發(fā)者可以使用它免費(fèi)且可靠地傳遞消息和通知。

使用 FCM,可以通知客戶端應(yīng)用存在可以同步的新電子郵件或其他數(shù)據(jù)。 您可以發(fā)送通知來(lái)重新吸引用戶和促進(jìn)用戶留存。 對(duì)于即時(shí)通訊等用例,一條消息可以將最大 4KB 的負(fù)載傳送至客戶端應(yīng)用。

1、準(zhǔn)備工作和連接Firebase

點(diǎn)擊查看Firebase系列之---初探Firebase

2、引用SDK和編寫代碼

    1. 引用Firebase Cloud Message SDK
      在app的build.gradle文件中添加:
dependencies {
   compile 'com.google.firebase:firebase-messaging:9.6.1'
}

    1. 接收和處理通知的兩種情況

下表來(lái)自官方文檔

應(yīng)用狀態(tài) 通知 數(shù)據(jù) 通知且攜帶數(shù)據(jù)
前臺(tái) onMessageReceived onMessageReceived onMessageReceived
后臺(tái) 系統(tǒng)托盤 onMessageReceived 通知:系統(tǒng)托盤數(shù)據(jù):Intent 的 extra 中

由上表可以得出,通知分為兩種:
當(dāng)應(yīng)用處于前臺(tái)時(shí)通知會(huì)回調(diào)onMessageReceived方法,如果想通知的話需要手動(dòng)通知,并取到攜帶的數(shù)據(jù)。
當(dāng)應(yīng)用處于后臺(tái)時(shí),F(xiàn)irebase sdk會(huì)自動(dòng)在系統(tǒng)托盤中通知,如果攜帶數(shù)據(jù)的話會(huì)回調(diào)onMessageReceived,如果點(diǎn)擊通知欄的話取數(shù)據(jù)需要通過(guò)Intent獲取。

    1. 添加通知所需Service和AndroidManifest.xml的配置

1.新建MyFirebaseMessagingService 繼承FirebaseMessagingService

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) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        // 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();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getBody());
        }

        // 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.
    }
    // [END receive_message]

    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * 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, CloudMessagingActivity.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_stat_ic_notification)
                .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());
    }
}

2、新建MyJobService繼承JobService

public class MyJobService extends JobService {

    private static final String TAG = "MyJobService";

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Log.d(TAG, "Performing long running task in scheduled job");
        // TODO(developer): add long running task here.
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return false;
    }

}

3、在AndroidManifest.xml中配置:

 <application
     //....
            >
         //...
        <!-- [START firebase_service] -->
        <service
            android:name=".messaging.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <!-- [END firebase_service] -->
        <service android:name=".messaging.MyJobService"
                 android:exported="false">
            <intent-filter>
                <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
            </intent-filter>
        </service>
</application

如果點(diǎn)擊通知欄的話為了避免重復(fù)打開Activity的話,需要設(shè)置Activity的啟動(dòng)模式為singleTask,意思為在當(dāng)前棧中如果存在此Activity實(shí)例就不會(huì)重新創(chuàng)建,且此時(shí)會(huì)回調(diào)onNewIntent()方法。配置如下:

<activity android:name=".activity.CloudMessagingActivity"
          android:launchMode="singleTask"> //設(shè)置啟動(dòng)模式
          <intent-filter>
             <action android:name="android.intent.action.MAIN"/>
             <category android:name="android.intent.category.LAUNCHER"/>
          </intent-filter>
</activity>

  • 4)編寫Activity和layout便于測(cè)試

Activity代碼:

public class CloudMessagingActivity extends BaseAppCompatActivity {

    private TextView mMessageText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloud_message);

        mMessageText = (TextView) findViewById(R.id.tv_message);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        StringBuilder builder = new StringBuilder();
        if (intent.getExtras() != null) {
            for (String key : intent.getExtras().keySet()) {
                Object value = intent.getExtras().get(key);
                builder.append("鍵:" + key + "-值:" + value + "\n");
            }
            mMessageText.setText(builder.toString());
        }
    }
}

activity_cloud_message很簡(jiǎn)單就一個(gè)TextView用于顯示接收到的值:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_horizontal_margin"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示內(nèi)容:"/>

</LinearLayout>

運(yùn)行效果如下:

前臺(tái)運(yùn)行

3、通過(guò)Firebase控制臺(tái)發(fā)送消息并測(cè)試

這里我們測(cè)試一下當(dāng)應(yīng)用在后臺(tái)運(yùn)行時(shí),控制臺(tái)發(fā)送消息并攜帶值的情況:

1、在Firebase控制臺(tái)填寫信息并發(fā)送:

填寫消息內(nèi)容
填寫標(biāo)題及攜帶的數(shù)據(jù)

2、手機(jī)執(zhí)行效果

可以看到手機(jī)已經(jīng)收到控制臺(tái)發(fā)送的消息:


接收通知

當(dāng)點(diǎn)擊通知欄的話會(huì)將在控制臺(tái)填寫的自定義數(shù)據(jù)獲取到并顯示(也有firebase默認(rèn)的key-value):

處理通知

順便我也測(cè)試了當(dāng)APP在前臺(tái)運(yùn)行時(shí)也可以接收到攜帶的數(shù)據(jù),如果需要的話對(duì)數(shù)據(jù)進(jìn)行處理即可:

處于前臺(tái)運(yùn)行

Firebase的Cloud Message功能就是這樣,本文只是此功能的一個(gè)測(cè)試用例,如要完成項(xiàng)目業(yè)務(wù),可以自行擴(kuò)展。如果錯(cuò)誤或建議,請(qǐng)多多指教。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容