Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FCM notification message are not received in android Oreo version?

Tags:

I have send FCM notification from server to users. It works fine(until api 25) but in Oreo when the application have not in background(services are closed) (or) completely closed .I am not getting any FCM notifications at this scenario but in Whatsapp works fine. here i have attached FCM code

Manifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.fcm">      <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@style/AppTheme">         <activity android:name=".MainActivity">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>         <service             android:name=".MyFirebaseMessagingService">             <intent-filter>                 <action android:name="com.google.firebase.MESSAGING_EVENT"/>             </intent-filter>             <intent-filter>                 <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>             </intent-filter>         </service>          <meta-data             android:name="com.google.firebase.messaging.default_notification_icon"             android:resource="@drawable/ic_stat_ic_notification" />          <meta-data             android:name="com.google.firebase.messaging.default_notification_color"             android:resource="@color/colorAccent" />          <meta-data             android:name="com.google.firebase.messaging.default_notification_channel_id"             android:value="fcm"/>          <meta-data android:name="firebase_messaging_auto_init_enabled"             android:value="false" />          <meta-data android:name="firebase_analytics_collection_enabled"             android:value="false" />      </application>  </manifest> 

app/gradle

apply plugin: 'com.android.application'  android {     compileSdkVersion 28     defaultConfig {         applicationId "com.fcm"         minSdkVersion 16         targetSdkVersion 28         versionCode 1         versionName "1.0"         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"     }     buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     } }  dependencies {     implementation fileTree(dir: 'libs', include: ['*.jar'])     implementation 'com.android.support.constraint:constraint-layout:1.1.2'     testImplementation 'junit:junit:4.12'     androidTestImplementation 'com.android.support.test:runner:1.0.2'     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'     implementation 'com.google.firebase:firebase-messaging:17.1.0' }  apply plugin: 'com.google.gms.google-services' 

MyFirebaseMessagingService.java

package com.fcm;  import android.app.Service; import android.util.Log;  import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage;  public class MyFirebaseMessagingService extends FirebaseMessagingService {      @Override     public void onNewToken(String s)      {     super.onNewToken(s);     }      @Override     public void onMessageReceived(RemoteMessage remoteMessage) {     super.onMessageReceived(remoteMessage);     Log.e("FCM Message Received","You Have FCM Message");     } } 

MainActivity.java

package com.nexge.fcm;  import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log;  import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult;  public class MainActivity extends AppCompatActivity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( this,  new OnSuccessListener<InstanceIdResult>() {             @Override             public void onSuccess(InstanceIdResult instanceIdResult) {                 String newToken = instanceIdResult.getToken();                 Log.e("newToken",newToken);             }         });     } } 
like image 894
Srinivasan M Avatar asked Jul 18 '18 13:07

Srinivasan M


People also ask

How do I get FCM notification?

For sending FCM notification payload you can use Firebase Cloud Messaging Tool in firebase console. And click on Send your first message. Then enter the Title and body field. If you wish to send it to a particular device then click on Send test message and enter the FCM registration token.

How FCM works when app is closed Android?

If the application is in the foreground onMessageReceived handle both data and notification messages. If the application is closed or in the background only data messages are delivered to onMessageReceived . notification messages are not delivered to onMessageReceived . So you can't customize your messages.

Is FCM completely free?

Firebase Cloud Messaging (FCM) provides a reliable and battery-efficient connection between your server and devices that allows you to deliver and receive messages and notifications on iOS, Android, and the web at no cost.


1 Answers

When you target Android 8.0 (API level 26), you must implement one or more notification channels. If your targetSdkVersion is set to 25 or lower, when your app runs on Android 8.0 (API level 26) or higher, it behaves the same as it would on devices running Android 7.1 (API level 25) or lower.

Note: If you target Android 8.0 (API level 26) and post a notification without specifying a notification channel, the notification does not appear and the system logs an error.

Note: You can turn on a new setting in Android 8.0 (API level 26) to display an on-screen warning that appears as a toast when an app targeting Android 8.0 (API level 26) attempts to post without a notification channel. To turn on the setting for a development device running Android 8.0 (API level 26), navigate to Settings > Developer options and enable Show notification channel warnings.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    String id = "id_product";    // The user-visible name of the channel.    CharSequence name = "Product";    // The user-visible description of the channel.    String description = "Notifications regarding our products";    int importance = NotificationManager.IMPORTANCE_MAX;    NotificationChannel mChannel = new NotificationChannel(id, name, importance);    // Configure the notification channel.    mChannel.setDescription(description);    mChannel.enableLights(true);    // Sets the notification light color for notifications posted to this    // channel, if the device supports this feature.    mChannel.setLightColor(Color.RED);    notificationManager.createNotificationChannel(mChannel); } 

Creating a Push Notification on Android Oreo

To create a notification, you will use the NotificationCompat.Builder class. The constructor which was used before took only Context as a parameter, but in Android O, the constructor looks like this –

NotificationCompat.Builder(Context context, String channelId) 

The following code snippet will show you how to create a notification –

Intent intent1 = new Intent(getApplicationContext(), Ma  inActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 123, intent1, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(),"id_product")        .setSmallIcon(R.drawable.flatpnicon) //your app icon        .setBadgeIconType(R.drawable.flatpnicon) //your app icon        .setChannelId(id)        .setContentTitle(extras.get("nt").toString())        .setAutoCancel(true).setContentIntent(pendingIntent)        .setNumber(1)        .setColor(255)        .setContentText(extras.get("nm").toString())        .setWhen(System.currentTimeMillis()); notificationManager.notify(1, notificationBuilder.build()); 

Android O gives you a few more functions to customize your notification –

setNumber() – allows you to set the number displayed in the long-press menu setChannelId() – allows you set the Channel Id explicitly if you are using the old constructor setColor() – allows a RGB value to put a color theme for your notification setBadgeIconType() – allows you to set an icon to be displayed in the long-press menu

for more info check example here

like image 189
Vishal Thakkar Avatar answered Oct 25 '22 23:10

Vishal Thakkar