Push notification onMessageReceived method in FirebaseMessagingService is not called? - android

I already Implemented the service in android manifest and still no response from the FirebaseMessagingService service. The weird thing is that the notification is successfully sent. When I tried to debug and add the breakpoint to the onMessageReceived method I can received the notification but when I install it first without attaching the debug the service is not called so no callback response from the FirebaseMessagingService. So basically FirebaseMessagingService will work if I debug the app but when it is not in debug no callback is called from the FirebaseMessagingService.
The phone that I used is Samsung galaxy J7pro android version OREO(API 27).
AndroidManifest.xml
added the following in the manifest file.
<service android:name=".services.InstanceIDListenerService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".services.NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
build.gradle(app)
added the following in the build.gradle file.
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-core:16.0.5'
}
apply plugin: 'com.google.gms.google-services'
NotificationService.java
public class NotificationService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// dbManagerPushNotification.DBManagerPushNotification(this);
if (remoteMessage.getData().size() > 0) {
Map<String, String> remoteMessage_getData = remoteMessage.getData();
String community_slug = remoteMessage_getData.get("community_slug");
String conversation_id = remoteMessage_getData.get("conversation_id");
String sender_id = remoteMessage_getData.get("sender_id");
final String message_id = remoteMessage_getData.get("message_id");
String message = remoteMessage_getData.get("message");
String convo_type = remoteMessage_getData.get("convo_type");
String created_at = remoteMessage_getData.get("created_at");
String title = remoteMessage_getData.get("title");
Log.i("push_notification", "onMessageReceived: " + message);
final String channel_id = title + community_slug;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("message", message);
intent.putExtra("message_id", message_id);
intent.putExtra("conversation_id", conversation_id);
intent.putExtra("sender_id", sender_id);
intent.putExtra("community_slug", community_slug);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), message_id.hashCode(), intent, 0);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
SpannableStringBuilder spannableStringBuilder_title = new SpannableStringBuilder(title);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
spannableStringBuilder_title.setSpan(boldSpan, 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channel_id, title, NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build();
mChannel.enableLights(true);
mChannel.setLightColor(Color.WHITE);
assert notificationManager != null;
notificationManager.createNotificationChannel(mChannel);
}
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), channel_id)
.setSmallIcon(R.drawable.ic_notif_logo)
.setColor(0xECEFF1)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setGroup(convo_type)
.setGroupAlertBehavior(GROUP_ALERT_CHILDREN)
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.selection_orange))
.setPriority(NotificationCompat.PRIORITY_MAX);
String community_notif = " " + community_slug + ": ";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(community_notif);
spannableStringBuilder.setSpan(new ForegroundColorSpan(getApplicationContext().getResources().getColor(R.color.selection_orange)), 0, community_notif.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
NotificationCompat.Builder summaryNotification = new NotificationCompat.Builder(getApplicationContext(), channel_id)
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_notif_logo)
.setStyle(new NotificationCompat.InboxStyle().setSummaryText(TextUtils.concat(spannableStringBuilder, title)).setBigContentTitle(TextUtils.concat(spannableStringBuilder, title)))
.setGroup(convo_type)
.setAutoCancel(true)
.setGroupAlertBehavior(GROUP_ALERT_CHILDREN)
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.selection_orange))
.setGroupSummary(true)
.setPriority(NotificationCompat.PRIORITY_MAX);
assert notificationManager != null;
notificationManager.notify(message_id.hashCode(), mBuilder.build());
notificationManager.notify(channel_id.hashCode(), summaryNotification.build());
}
}
}

Related

Oreo failed to post notification on channel null

i am trying to make notification push using FCM but every time when i am trying to send notification my Emulator always toasting failed to post notification on channel null,
i have trying many ways about posting notification on channel, but none of it is correct
i am using 'com.google.firebase:firebase-messaging:10.2.0'
here is my code
private void sendMyNotification(String message) {
int NOTIFICATION_ID = 234;
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";
CharSequence name = "my_channel";
String Description = "This is my channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setDescription(Description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mChannel.setShowBadge(false);
notificationManager.createNotificationChannel(mChannel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("LALALLA")
.setContentText(message);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
} else {
//On click of notification it redirect to this Activity
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Firebase Push notification")
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
notificationManager.notify(0, notificationBuilder.build());
}
my manifest.xml
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
i solved my problem by upgrading my 'com.google.firebase:firebase-messaging:10.2.0' to newer version
for example , now iam using : 'com.google.firebase:firebase-messaging:11.8.0'

Notification doesn't notify

I am making MQTT client app using paho MQTT client dependency.
Implementing code in a Background Service. and everything works well except the Notification isn't working!
Service code snippet is here:
My Codes occurs inside the TimeDisplayTimerTask inner-class.
This code located at the callback function :
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
mIntent = new Intent(getApplicationContext(), MainActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, 0);
createNotificationChannel();
Toast.makeText(getApplicationContext(),"A message received : "+ new String(message.getPayload()),Toast.LENGTH_SHORT).show();
vibrator.vibrate(500);
myRingtone.play();
mBuilder .setContentTitle("Message received at : " + mTopic)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentText("Message : "+ new String(message.getPayload()));
mNotificationManager.notify(0, mBuilder.build());
}
And this code creates a notification channel (as Google developers guide mentioned to write):
Posted with help of this answer.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String chanel_id = "3000";
CharSequence name = "Mqtt message";
String description = "Message arrived";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
mNotificationManager = getSystemService(NotificationManager.class);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
mBuilder = new NotificationCompat.Builder(getApplicationContext(), chanel_id);
}
else
{
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext());
}
}
When it receives a message, A toast message appears holding the message.
But it doesn't push notification.
Checked Apps and Notifications, All notifications are allowed.
SOLVED :
the setter method .setSmallIcon must be called to successfully build a notification.
Which was not important to me.

Notifications is not shown in some devices

I use this code to show notifications users of my app.
On some devices, this code works perfectly, but some devices do not show a notification at all.
Is someone know what is the problem?
private void sendNotification(String title, String messageBody, Map<String, String> allData) {
Intent intent = new Intent(this, ReferralPage.class);
intent.putExtra("title", title);
intent.putExtra("text", messageBody);
String tid = allData.get("tid");
intent.putExtra("tid", tid);
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, "CH_"+tid)
.setSmallIcon(com.escodes.R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_MAX);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
long time = new Date().getTime();
String tmpStr = String.valueOf(time);
String last4Str = tmpStr.substring(tmpStr.length() - 5);
int notificationId = Integer.valueOf(last4Str);
notificationManager.notify(notificationId, notificationBuilder.build());
}
You need to add a notification channel for API 26 and above, like this:
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "ID_OF_THE_CHANNEL";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"name_of_the_channel",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setContentTitle("title")
.setContentText("text")
...
...
.build();
}

Firebase notification works in background but doesn't appear in Foreground in Oreo

I am trying to make push notification using Firebase to my app. I tried it and it works perfectly in the background in Oreo, but when I try to open the app and send a notification from another account, the notification does not appear.
How do I solve this and where is the problem in my code?
This is part of the code of my service:
public class FirebaseMessagingService extends
com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
Intent resultIntent = new Intent(this, MainAdsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int id = (int) System.currentTimeMillis();
builder.setContentIntent(pendingIntent);
startForeground(id,builder.build());
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());
}
}
Android manifest file:
<service
android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
Cloud functions
const functions = require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const api = admin.firestore()
api.settings({timestampsInSnapshots: true})
exports.fuync=functions
.firestore.document("Users/{userid}/notification/{notification_id}")
.onWrite((change,context)=>{
const userid=context.params.userid;
const notification_id=context.params.notification_id;
return admin.firestore().collection('Users')
.doc(userid).collection('notification')
.doc(notification_id).get().then(queryRes
ult=>{
const fromuserid=queryResult.data().from;
const frommessage=queryResult.data().message;
const
fromdata=admin.firestore()
.collection('Users').doc(fromuserid).get();
const todata=admin.firestore()
.collection('Users').doc(userid).get();
return Promise.all([fromdata,todata]).then(result=>{
const fromname=result[0].data().name;
const toname=result[1].data().name;
const tokenid=result[1].data().token_id;
//return console.log("from :" +fromname + "TO: " +toname);
const payload= {
notification: {
title : "notification from" +fromname,
body : frommessage,
icon : "default"
}
};
return admin.messaging().sendToDevice(tokenid,payload).then(result=>{
return console.log("NOTIFICATION SENT.");
});
});
});
});
build gradle
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.amr.app"
minSdkVersion 18
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner
buildToolsVersion '27.0.3'
}
This is the solution I have done and works perfectly in foreground and background for Oreo version and higher versions.
Creating a notification channel is very crucial. The most important thing is the String id inside NotificationChannel channel = new NotificationChannel().
it must be the one provided by firebase which is : default_notification_channel_id
and the code will be like this:
private static final CharSequence NAME = "amro";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
//____ID _____
int id = (int) System.currentTimeMillis();
//_____NOTIFICATION ID'S FROM FCF_____
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationCompat.Builder builder =
new NotificationCompat
.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
//_____REDIRECTING PAGE WHEN NOTIFICATION CLICKS_____
Intent resultIntent = new Intent(this, ProfileActivity.class);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(pendingIntent);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
int importance = NotificationManager.IMPORTANCE_HIGH;
String channelID = BuildConfig.APPLICATION_ID;
NotificationChannel channel = new NotificationChannel
(getString(R.string.default_notification_channel_id), BuildConfig.APPLICATION_ID, importance);
channel.setDescription(channelID);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
//assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(id, builder.build());
}
Since android oreo there is Channel
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.
try to using support library 26 or later and check this Create and Manage Notification Channels
try to use this method to create NotificationCompat.Builder
public NotificationCompat.Builder initChannels() {
if (Build.VERSION.SDK_INT < 26) {
return new NotificationCompat.Builder(this);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = BuildConfig.APPLICATION_ID;
NotificationChannel channel = new NotificationChannel(id, BuildConfig.APPLICATION_ID, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(BuildConfig.APPLICATION_ID);
notificationManager.createNotificationChannel(channel);
return new NotificationCompat.Builder(this, id);
}
the create new instance from this method
NotificationCompat.Builder builder = initChannels();
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
try
String messageTitle = remoteMessage.getData().getTitle();
String messageBody = remoteMessage.getData().getBody();
First add logs in onMessageArrived()
Log.d("Firebase PM service", "onMessageArrived called");
and check if you are getting this log in LogCat.
If you don't, then something is not working properly on Firebase end.
If you are receiving it, then it means you are doing something wrong after getting push msg(i.e. not displaying notification properly). Also check LogCat whether any exception is thrown or not.
Then post your replay.
Use the below code in FirebaseMessagingService.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = “Your channel name, It will be visible in app setting”;
String description =“Description for your channel”;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(SOME_CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat
.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
Intent resultIntent = new Intent(this, MainAdsActivity.class);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
int id = (int) System.currentTimeMillis();
builder.setContentIntent(pendingIntent);
startForeground(id,builder.build());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());
}
}

FCM notification not receiving

I have an application which will get FCM notifications.It recived fine on devices up to marshmellow.When I insatlled it on oreo device it getting toast which says notificaton channel is null.I searched on google and I found that Notification channels are required for receiving notifications on API above 26. I added a notification channel but it shows the toast again.No notification.
My AppFirebaseMessagingService
public class AppFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title;
String description;
String click_action;
if(remoteMessage.getData()!=null) {
title = (remoteMessage.getData().get("title") == null || remoteMessage.getData().get("title").equals("")) ? "null" : remoteMessage.getData().get("title");
description = (remoteMessage.getData().get("body") == null || remoteMessage.getData().get("body").equals("")) ? "null" : remoteMessage.getData().get("body");
click_action = (remoteMessage.getData().get("click_action") == null || remoteMessage.getData().get("click_action").equals("")) ? "null" : remoteMessage.getData().get("click_action");
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.
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);
}
//Notification----------------------
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(AppFirebaseMessagingService.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(title);
mBuilder.setContentText(description);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
SharedPreferences sharedpreferences = getSharedPreferences(Common.preferenceName, Context.MODE_PRIVATE);
String RoleCSV=sharedpreferences.getString(Common.roleCSV,"");
}
}
}
My Androidmanifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".AppFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".AppFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".Login"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"
android:theme="#style/Theme.Design.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomeScreen"
android:configChanges="orientation|screenSize" />
<activity
</application>
I write the piece of code for checking if the device is oreo
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager1 = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager1.createNotificationChannel(notificationChannel);
}
mNotification = builder
.setLargeIcon(image)/*Notification icon image*/
.setContentText(messageBody)
.setSmallIcon(R.drawable.dhlone)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image).bigLargeIcon(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setBadgeIconType(R.drawable.dhlone)
.setAutoCancel(true)
.setSmallIcon(getNotificationIcon())
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext()
.getResources(),R.drawable.dhlone))
.build();
notificationManager1.notify(/*notification id*/0, mNotification);
private fun createNotification(title: String, message: String) {
val resultIntent = Intent(this, LoginActivity::class.java)
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val mBuilder = NotificationCompat.Builder(this)
mBuilder.setSmallIcon(R.drawable.ic_stat_name)
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent)
val mNotificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableVibration(true)
notificationChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID)
mNotificationManager.createNotificationChannel(notificationChannel);
}
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}

Categories

Resources