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

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

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

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

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

Cloud Messaging

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

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

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

點擊查看Firebase系列之---初探Firebase

2杀怠、引用SDK和編寫代碼

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

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

下表來自官方文檔

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

由上表可以得出火窒,通知分為兩種:
當(dāng)應(yīng)用處于前臺時通知會回調(diào)onMessageReceived方法,如果想通知的話需要手動通知驮肉,并取到攜帶的數(shù)據(jù)。
當(dāng)應(yīng)用處于后臺時已骇,F(xiàn)irebase sdk會自動在系統(tǒng)托盤中通知离钝,如果攜帶數(shù)據(jù)的話會回調(diào)onMessageReceived,如果點擊通知欄的話取數(shù)據(jù)需要通過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

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

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

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

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很簡單就一個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>

運行效果如下:

前臺運行

3碘橘、通過Firebase控制臺發(fā)送消息并測試

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

1吱肌、在Firebase控制臺填寫信息并發(fā)送:

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

2痘拆、手機執(zhí)行效果

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


接收通知

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

處理通知

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

處于前臺運行

Firebase的Cloud Message功能就是這樣氮墨,本文只是此功能的一個測試用例纺蛆,如要完成項目業(yè)務(wù),可以自行擴展规揪。如果錯誤或建議桥氏,請多多指教。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末猛铅,一起剝皮案震驚了整個濱河市字支,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖祥款,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件清笨,死亡現(xiàn)場離奇詭異,居然都是意外死亡刃跛,警方通過查閱死者的電腦和手機抠艾,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來桨昙,“玉大人检号,你說我怎么就攤上這事⊥芾遥” “怎么了齐苛?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長桂塞。 經(jīng)常有香客問我凹蜂,道長,這世上最難降的妖魔是什么阁危? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任玛痊,我火速辦了婚禮,結(jié)果婚禮上狂打,老公的妹妹穿的比我還像新娘擂煞。我一直安慰自己,他們只是感情好趴乡,可當(dāng)我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布对省。 她就那樣靜靜地躺著,像睡著了一般晾捏。 火紅的嫁衣襯著肌膚如雪蒿涎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天惦辛,我揣著相機與錄音同仆,去河邊找鬼。 笑死裙品,一個胖子當(dāng)著我的面吹牛俗批,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播市怎,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼岁忘,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了区匠?” 一聲冷哼從身側(cè)響起干像,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤帅腌,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后麻汰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體速客,經(jīng)...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年五鲫,在試婚紗的時候發(fā)現(xiàn)自己被綠了溺职。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡位喂,死狀恐怖浪耘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情塑崖,我是刑警寧澤七冲,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站规婆,受9級特大地震影響澜躺,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜抒蚜,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一掘鄙、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧削锰,春花似錦、人聲如沸毕莱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽朋截。三九已至蛹稍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間部服,已是汗流浹背唆姐。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留廓八,地道東北人奉芦。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像剧蹂,于是被迫代替她去往敵國和親声功。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,747評論 2 361

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