轉(zhuǎn)載請注明出處:http://www.reibang.com/p/3b880a09f754
本文出自Shawpoo的簡書
我的博客:CSDN博客
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
2杀怠、引用SDK和編寫代碼
- 引用Firebase Cloud Message SDK
在app的build.gradle文件中添加:
- 引用Firebase Cloud Message SDK
dependencies {
compile 'com.google.firebase:firebase-messaging:9.6.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獲取褪储。
- 添加通知所需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ā)送:
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ù),可以自行擴展规揪。如果錯誤或建議桥氏,請多多指教。