instead of opening activity, I found that the broadcast receiver can do the trick but it's not working its is not sending an intent to my broadcast receiver. I don't know any workaround. eventually, I have to call the notification from a service. please give me a way to run a function on clicking the notification
Broadcast receiver class
class broadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d(Constants.TAG, "onReceive")
}
}
main activity code
receiver = broadcastReceiver()
registerReceiver(receiver, IntentFilter("com.example.andy.CUSTOM_INTENT"))
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent(this, broadcastReceiver::class.java)
val pendingIntent = PendingIntent.getActivity(this, 5, intent, PendingIntent.FLAG_UPDATE_CURRENT)
// RemoteViews are used to use the content of
// some different layout apart from the current activity layout
val contentView = RemoteViews(packageName, R.layout.activity_after_notification)
// checking if android version is greater than oreo(API 26) or not
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.GREEN
notificationChannel.enableVibration(false)
notificationManager.createNotificationChannel(notificationChannel)
builder = Notification.Builder(this, channelId)
.setContent(contentView)
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background))
.setContentIntent(pendingIntent)
} else {
builder = Notification.Builder(this)
.setContent(contentView)
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background))
.setContentIntent(pendingIntent)
}
notificationManager.notify(1234, builder.build())
}
Related
I have implemented a broadcast receiver to ask the user to restart the app if it is killed. I have confirmed that the broadcast receiver is being called fine, and it runs the below line but for some reason, I am not getting any notification.
Here is the code,
class ForegroundLocationServicesRestarter : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent != null) {
if (intent.action != ForegroundLocationService.ACTION_RESTART_LOCATION_UPDATES) {
return
}
}
val notificationChannelId = "restartDeliveryApp"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(notificationChannelId, "location_notif_chan", NotificationManager.IMPORTANCE_MAX)
val manager = context.getSystemService(LifecycleService.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
val fullScreenIntent = Intent(context, DeliveryManActivity::class.java)
fullScreenIntent.putExtra("RESTART_TRIGGERED", true)
val fullScreenPendingIntent = PendingIntent.getActivity(
context, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
NotificationCompat.Builder(context, notificationChannelId)
.setSmallIcon(R.drawable.ic_truck_red)
.setContentTitle(context.getString(R.string.restarter_title))
.setContentText(context.getString(R.string.restarter_message))
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setFullScreenIntent(fullScreenPendingIntent, true)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.build()
}
}
The notification channel is unique, the app has notification permission and also, full intent permission in the manifest. Any help is highly appreciated.
Plus there is already one service notification, does that impact this in any way?
was not pushing notifications into the system to display! Just need to do this!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(notificationChannelId, "location_notif_chan", NotificationManager.IMPORTANCE_MAX)
val manager = context.getSystemService(LifecycleService.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
val dmIntent = Intent(context, DeliveryManActivity::class.java)
dmIntent.putExtra("RESTART_TRIGGERED", true)
val dmPendingIntent = PendingIntent.getActivity(
context, 0, dmIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
// Prepare a notification with vibration, sound and lights
val builder = NotificationCompat.Builder(context, notificationChannelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_truck_red)
.setContentTitle(context.getString(R.string.restarter_title))
.setContentText(context.getString(R.string.restarter_message))
.setLights(Color.RED, 1000, 1000)
.setVibrate(longArrayOf(0, 400, 250, 400))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(dmPendingIntent)
Pushy.setNotificationChannel(builder, context)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(7, builder.build()) // same notification id to override
Method to create a Notification Channel
private fun createChannel(notificationManager: NotificationManager) {
val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setLegacyStreamType(AudioManager.STREAM_RING)
.build()
val incomingPhoneCallChannel = NotificationChannel(
mNotificationManager.INCOMING_PHONE_CALL_CHANNEL_ID, "Incoming phone call",
NotificationManager.IMPORTANCE_HIGH
).apply {
setSound(uri, audioAttributes)
vibrationPattern = mNotificationManager._VIBRATION_PATTERN
enableVibration(true)
}
notificationManager.createNotificationChannel(incomingPhoneCallChannel)
}
Method to notify about the call
override fun notify(context: Context) {
val notificationManager = mNotificationManager.notificationManager
val notificationChannel = notificationManager.getNotificationChannel(mNotificationManager.INCOMING_PHONE_CALL_CHANNEL_ID)?: createChannel(notificationManager)
val contentTitle = "Incoming Call"
val contentIntent = Intent(context, PhoneCallReceiver::class.java)
val pendingIntent =
PendingIntent.getBroadcast(context, 0, contentIntent, PendingIntent.FLAG_IMMUTABLE)
val ringtone =RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
var builder = NotificationCompat.Builder(
context,
mNotificationManager.INCOMING_PHONE_CALL_CHANNEL_ID
)
.setContentTitle(contentTitle)
.setContentIntent(pendingIntent)
.setContentText("phone call")
.setColor(ContextCompat.getColor(context, R.color.ic_launcher_background))
.setCategory(NotificationCompat.CATEGORY_CALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_phone_black_24dp)
.setOngoing(true)
.setSound(ringtone)
builder.setVibrate(mNotificationManager._VIBRATION_PATTERN
val notification = builder.build()
notification.flags = Notification.FLAG_INSISTENT
notificationManager.notify("Incoming Call", mId, notification)
}
The above code does give me notification with a default notification that sounds like a single "TING!!". It doesn't change the sound even if I select different Ringtones from the notification channel settings and doesn't vibrate at all.
Make sure the audio permission is allowed:
// Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Change TYPE_RINGTONE to TYPE_NOTIFICATION
I'm using Kotlin and Android Studio to try and push a Notification in a test app. I followed the instructions in the Android Developers site on How to create a Notification (https://developer.android.com/training/notify-user/build-notification) but I seem to be doing something wrong as my Notification is not showing anywhere. Here's my code:
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager = message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
I really don't know what I'm missing so I would be grateful for any help.
According to your code, you are not creating a Notification channel.
Notification channel is necessary from Android Oreo and above
So if you are running the app Android O and above devices without a notification channel, your notification won't show up.
Create Notification Channel
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "all_notifications" // You should create a String resource for this instead of storing in a variable
val mChannel = NotificationChannel(
channelId,
"General Notifications",
NotificationManager.IMPORTANCE_DEFAULT
)
mChannel.description = "This is default channel used for all other notifications"
val notificationManager =
mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
Then create a notification using the same channelId while creating a notification.
createNotificationChannel()
val channelId = "all_notifications" // Use same Channel ID
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context, channelId) // Create notification with channel Id
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
Hope it helps.
try something like
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Don't forget this check
val channel = NotificationChannel (
channelId,
"my_notification",
NotificationManager.IMPORTANCE_HIGH
)
channel.enableLights(true)
channel.lightColor = Color.GREEN
channel.enableVibration(false)
val builder = NotificationCompat.Builder(this.context, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
mNotificationManager.createNotificationChannel(channel)//Notice this
mNotificationManager.notify(123, builder.build())
}
else {
//Create Notifcation for below Oreo
}
Does your Logcat say something like:
E/NotificationManager: notifyAsUser: tag=null, id=123, user=UserHandle{0}
Also have a look at your line:
val intent = Intent(context, Profile::class.java)
IF all else fails create a test Actvity with hello world.
And then make the line look like:
val intent = Intent(context, testActivity::class.java)
Remember to add the activity to your Manifest
The following line
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
should not have a semi colon. Kotin doesn't need this.
Is Profile your Class or System Class?
Try out this method and you can pass message and title dynamically :
private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, Profile::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
I Have problem with my notification.
First way - I open my app, then I push notification from FCM first time, I click the notif, my code executed, I push again for second time, I click my notif, my code still execute, I try more more time is worked well.
Second way - My app still close, I push notif from FCM first time, then I Click the notif, so my app will open and my code executed, then I push notif again for second time, my code NOT executed, I try more more time still NOT working.
until I swipe my app, and try again, the problem still happen.
this is my code
class MyFirebaseMessagingService : FirebaseMessagingService() {
var userInformation = AccountTableDao()
val sp: SharedPreferences by lazy { SharedPreference.instance }
val gad: GetAccountData by lazy { AccountDatabase.instance }
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("firebase", "INSTANCE ID ===> $token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
remoteMessage?.let {
sendNotification(it.data)
}
}
private fun sendNotification(messageData: Map<String, String>) {
var status = messageData.get("status")
val uuid = messageData.get("uuid")
val restaurantId = messageData.get("restaurantId")
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val titleText = messageData.get("title").toString()
val contentText = messageData.get("body").toString()
val intent = Intent(applicationContext, RestaurantMenuActivity::class.java)
intent.putExtra(Argument.NOTIF_UUID, uuid)
intent.putExtra(Argument.NOTIF_RESTAURANT_ID, restaurantId)
intent.putExtra(Argument.NOTIF_STATUS, status)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent = PendingIntent.getActivity(applicationContext,System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel("appety", "appety_notification", NotificationManager.IMPORTANCE_HIGH)
notificationManager .createNotificationChannel(notificationChannel)
notificationManager.notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setChannelId(System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle(NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
}
else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
} else {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.build())
}
}
}
companion object {
private val TAG = "token"
}
}
and manifest
<service
android:name=".service.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Why Pending Intent not working and how to fix that.
Sorry for my english and regard.
You should try setAutoCancel() method when creating the notification.
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder summary = new NotificationCompat.Builder(this);
summary.setAutoCancel(true);
And if you passing an intent to the notification, then use this
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
When my app is open, notification works perfectly but when in background it doesn't work .I want the notification to be displayed even when my app is killed or closed in my phone. But it is not working. Here is my code :-
1) MyFirebaseMessagingService.kt :-
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
showNotification(remoteMessage!!)
Log.e("fcm", "HElloo Call")
}
#SuppressLint("WrongConstant")
private fun showNotification(message: RemoteMessage) {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val i = Intent(this, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
val androidChannel = NotificationChannel("1",
"sdccscsc", NotificationManager.IMPORTANCE_DEFAULT)
androidChannel.enableLights(true)
androidChannel.enableVibration(true)
androidChannel.lightColor = Color.GREEN
androidChannel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val builder = NotificationCompat.Builder(this, "1")
.setAutoCancel(true)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setSmallIcon(R.drawable.main_logo)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent)
manager.createNotificationChannel(androidChannel)
}
val i = Intent(this, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setSmallIcon(R.drawable.main_logo)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent)
manager.notify(0, builder.build())
}
Check your logcat if you are receiving the notification. IS your notification being displayed in the system tray?
There are two types of Message types
Notification message
FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-visible keys and an optional data payload of custom key-value pairs.
Data message
Client app is responsible for processing data messages. Data messages have only custom key-value pairs.
as per my comment
You need to send notification data in Data messages
SAMPLE FORMAT
{
"message":{
"token":"your token",
"data":{
"key1" : "value1",
"key2" : "value2",
"key3" : "value4",
}
}
}
EDIT
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Intent intent = new Intent(this, YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
intent.putExtra("ID",object.getString("data"));
} catch (JSONException e) {
e.printStackTrace();
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "Your_channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorDarkBlue))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_MAX);
notificationManager.notify(1000, notificationBuilder.build());
notificationManager.cancelAll();