Support notification channel in API 26 or newer

This commit is contained in:
Jirawat Karanwittayakarn 2017-10-17 17:34:12 +07:00
parent ab4d888c6f
commit 818131d51e
9 changed files with 56 additions and 36 deletions

View File

@ -14,6 +14,7 @@ FCM is just a demo of Android Application which implement Firebase Cloud Messagi
* Send message with **a token**, **token group**, **a topic**, **condition**
* Handle message both **foreground** and **background**
* Customize notification
* Support notification channel for Android 0 or newer
## Limitation in the message payload
* Notification : 2KB limit and a predefined set of user-visible keys

View File

@ -1,13 +1,13 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion compileAndTargetSdk
compileSdkVersion compileAndTargetSdkVersion
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.example.fcm"
minSdkVersion 25
targetSdkVersion compileAndTargetSdk
minSdkVersion compileAndTargetSdkVersion
targetSdkVersion compileAndTargetSdkVersion
versionCode 1
versionName "1.0"
resConfigs('en', 'xxxhdpi')

View File

@ -11,6 +11,18 @@
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/notification_channel_id" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">

View File

@ -32,7 +32,7 @@ public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(txt);
mTextView = findViewById(txt);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
@ -91,9 +91,9 @@ public class MainActivity extends AppCompatActivity {
jNotification.put("sound", "default");
jNotification.put("badge", "1");
jNotification.put("click_action", "OPEN_ACTIVITY_1");
jNotification.put("icon", "ic_launcher");
jNotification.put("icon", "ic_notification");
jData.put("picture_url", "http://opsbug.com/static/google-io.jpg");
jData.put("picture", "http://opsbug.com/static/google-io.jpg");
switch(type) {
case "tokens":

View File

@ -1,6 +1,7 @@
package com.example.fcm;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
@ -9,6 +10,7 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
@ -21,32 +23,29 @@ import java.net.URL;
import java.util.Map;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String FCM_PARAM = "picture";
private static final String CHANNEL_NAME = "FCM";
private static final String CHANNEL_DESC = "Firebase Cloud Messaging";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(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.
RemoteMessage.Notification notification = remoteMessage.getNotification();
Map<String, String> data = remoteMessage.getData();
Log.e("FROM", remoteMessage.getFrom());
Log.d("FROM", remoteMessage.getFrom());
sendNotification(notification, data);
}
private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle bundle = new Bundle();
bundle.putString("picture_url", data.get("picture_url"));
bundle.putString(FCM_PARAM, data.get(FCM_PARAM));
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, getString(R.string.notification_channel_id))
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
@ -54,16 +53,16 @@ public class MyFirebaseMessagingService extends FirebaseMessagingService {
//.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.win))
.setContentIntent(pendingIntent)
.setContentInfo("Hello")
.setLargeIcon(icon)
.setColor(Color.RED)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getColor(R.color.colorAccent))
.setLights(Color.RED, 1000, 300)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.mipmap.ic_launcher);
.setSmallIcon(R.drawable.ic_notification);
try {
String picture_url = data.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
String picture = data.get(FCM_PARAM);
if (picture != null && !"".equals(picture)) {
URL url = new URL(picture);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(
new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
@ -74,6 +73,21 @@ public class MyFirebaseMessagingService extends FirebaseMessagingService {
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
getString(R.string.notification_channel_id), CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
);
channel.setDescription(CHANNEL_DESC);
channel.setShowBadge(true);
channel.canShowBadge();
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}

View File

@ -10,7 +10,7 @@ public class SecondActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView txt = (TextView) findViewById(R.id.textView);
TextView txt = findViewById(R.id.textView);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {

View File

@ -1,6 +0,0 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

View File

@ -1,13 +1,12 @@
<resources>
<string name="app_name">FCM</string>
<string name="btn_send_token">Send Token</string>
<string name="btn_send_tokens">Send Tokens</string>
<string name="btn_send_topic">Send Topic</string>
<string name="btn_show_token">Show Token</string>
<string name="btn_subscribe_news">Subscribe (News)</string>
<string name="btn_unsubscribe_news">Unsubscribe (News)</string>
<string name="notification_channel_id">default</string>
<string name="result">Something will happen here&#8230;</string>
<string name="subscribed">Subscribed to news topic</string>
<string name="unsubscribed">Unsubscribed from news topic</string>

View File

@ -6,7 +6,7 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-beta7'
classpath 'com.android.tools.build:gradle:3.0.0-rc1'
classpath 'com.google.gms:google-services:3.1.0'
}
}
@ -25,5 +25,5 @@ task clean(type: Delete) {
ext {
supportLibraryVersion = '26.1.0'
firebaseLibraryVersion = '11.4.2'
compileAndTargetSdk = 26
compileAndTargetSdkVersion = 26
}