this permission screen At the moment, when notifications are shown on MIUI, notifications do not pop up . When viewing the settings, I found that on some XIOMI devices, this setting is disabled. Is there any way to enable it by default, or check if it is enabled
NotificationCompat.Builder(context, SOME_CHANNEL_ID).apply {
setupNotificationData(newRide)
setTimeoutAfter(1000* someTimeout.toLong())
setContentTitle(context.getString(R.string.offer_description))
setContentText(context.getString(R.string.offer_new_event))
setCustomHeadsUpContentView(createHeadsUpContentView())
setSmallIcon(R.drawable.logo_notification)
setContentIntent(pendingIntent)
setSound(getSoundUri())
setStyle(NotificationCompat.DecoratedCustomViewStyle())
priority = NotificationCompat.PRIORITY_MAX
setDeleteIntent(getDeleteAction())
setVibrate(longArrayOf(500, 500, 500, 500, 500))
setOngoing(true)
}
private fun getNotificationChannelForOffer() =
NotificationChannel(
SOME_CHANNEL_ID, OSOME_CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH
).apply {
setSound(
getOfferSoundUri(),
audioAttributes
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
canBubble()
}
shouldVibrate()
setBypassDnd(true)
enableVibration(true)
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
vibrationPattern = longArrayOf(500, 500, 500, 500, 500)
}
I've tried to use
setCustomHeadsUpContentView(createHeadsUpContentView())
but notifications do not overlay without this permission .
Add this
permission to Manifest
Related
I am trying to get custom notification sounds working for my flutter based Android app that uses Android version 26 with notification channels.
I have configured both the node.js server code, and the android app to use a notification channel with a custom sound.
My android code that initialises the channel looks as follows...
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val sound: Uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/" + R.raw.app_alert)
val mChannel = NotificationChannel("app_alerts", "app_alerts_2", NotificationManager.IMPORTANCE_HIGH)
val audioAttributes: AudioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
mChannel.setSound(sound , audioAttributes)
mChannel.description = "Important app Notifications"
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
}
And my node.js code is as follows...
const { messaging } = require('firebase-admin');
var admin = require('firebase-admin');
console.log(process.cwd());
var serviceAccount = require("path to my credentials");
const topic = 'all';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const payload = {
notification: {
title: "Test Notification",
body: "This is just a test",
},
android: {
notification: {
channelId: "app_alerts",
sound: 'app_alert'
},
},
apns: {
payload: {
aps: {
sound: 'app_alert.wav'
},
},
},
topic: 'all'
};
admin.messaging().send(payload).then(response => {
console.log("Successfully sent message:", response);
})
I have gone into my Android settings and confirmed that the notification channel has been created as expected...yet the custom sound does not play.
Since I got to have push notifications working as required when app was in both background and foreground, I have executed 30-40 notifications while testing (in 2 days), all of them sounding properly when arrived to android device (my custom notification channel also appeared in device settings as expected).
Suddenly, notifications continue arriving but without the sound (and custom notification channel does not appear in settings as before did). Since this, it is impossible for me to have sound back on notifications (neither background nor foreground).
Have not changed any involved code. I think sound has stopped because the notification channel is not being created for some reason. Have anyone experienced this or can help me?
Key code for case 'App in background':
1. Manifest.
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="my_fcm_default_channel" />
2. Launching activity - onCreate():
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
val channelName = "Custom notification channel"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationManager = getSystemService(NotificationManager::class.java)
val channel = NotificationChannel("my_fcm_default_channel",
channelName,
NotificationManager.IMPORTANCE_HIGH)
channel.setSound(defaultSoundUri, AudioAttributes.Builder().build()) // Not working
channel.enableLights(true)
channel.lightColor = Color.WHITE
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(100, 200, 100, 200, 100, 200, 100)
notificationManager.createNotificationChannel(channel)
}
3. Cloud function node.js snippet code:
// Notification details.
const payload = {
notification: {
title: 'Some title',
body: 'Some message',
sound: 'default',
click_action: "OPEN_ACTIVITY_3"
},
data: {
name: 'notification_3'
}
};
UPDATE:
Key code for case 'App in foreground':
1. MyFirebaseMessagingService - onMessageReceived():
val name = remoteMessage.data["name"] ?: ""
var intent: Intent? = null
when (name) {
"notification_1" -> {
intent = Intent(this, Activity1::class.java)
}
"notification_2" -> {
intent = Intent(this, Activity2::class.java)
}
"notification_3" -> {
val clickAction = remoteMessage.notification?.clickAction
clickAction?.let {
intent = Intent(clickAction)
intent?.putExtra("name", name)
}
}
"notification_4" -> {
intent = Intent(this, Activity4::class.java)
}
}
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, "my_fcm_default_channel")
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark) // Dummy icon
.setContentTitle(remoteMessage.notification?.title ?: "")
.setContentText(remoteMessage.notification?.body ?: "")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(longArrayOf(100, 200, 100, 200, 100, 200, 100))
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL) // this line sets the default vibration and sound for notification
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("my_fcm_default_channel",
"Custom notification channel",
NotificationManager.IMPORTANCE_HIGH)
channel.setSound(defaultSoundUri, AudioAttributes.Builder().build()) // Not working
channel.enableLights(true)
channel.lightColor = Color.WHITE
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(100, 200, 100, 200, 100, 200, 100)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
Everything is working fine in debug mode and if I run, flutter run --release.
But custom sound is not working if I generate release build and running using that.
I am using flutter.
here is the code,
Future _showNotificationWithSound(title, message) async {
var vibrationPattern = Int64List(4);
vibrationPattern[0] = 0;
vibrationPattern[1] = 1000;
vibrationPattern[2] = 5000;
vibrationPattern[3] = 2000;
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'added_my_channel_id',
'abc',
'abc',
icon: 'app_icon',
playSound: true,
sound: RawResourceAndroidNotificationSound('notifiysound'),
vibrationPattern: vibrationPattern,
enableLights: true,
color: const Color.fromARGB(255, 255, 0, 0),
ledColor: const Color.fromARGB(255, 255, 0, 0),
ledOnMs: 1000,
ledOffMs: 500);
var iOSPlatformChannelSpecifics =
IOSNotificationDetails(sound: 'notifiysound.mp3');
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
flutterLocalNotificationsPlugin. show(
0, title, message,platformChannelSpecifics);
}
You're probably missing a keep.xml in raw folder. Then the files won't be included in build but only available when running in debug mode. See last answer here: Flutter local notification custom sound doesn't work (path issue)
Add full path instead of file name
Incorret: IOSNotificationDetails(sound: 'notifiysound.mp3');
Correct: IOSNotificationDetails(sound: 'assets/notifiysound.mp3');
please put below code in your MainActivity.java file in android folder.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
Uri soundUri=Uri.parse("android.resource://"+getApplicationContext()
.getPackageName() + "/" + R.raw.alert);
AudioAttributes audioAttributes =AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel channel = new
NotificationChannel("channelId","channelName",
NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
and put your Custom sound mp3 file in your projects
android/app/src/raw/mp3 file
Note: it will only work for Android custom sound
i'm using FCM and follow instructions on firebase site but notifications not working when app in background
i already sync gradle library and download json file and sync done but not notifications recieved when app in background
app gradle
dependencies {
///////
}
apply plugin: 'com.google.gms.google-services'
dependencies {
classpath 'com.android.tools.build:gradle:3.5.1'
classpath 'com.google.gms:google-services:4.3.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
You have to add
classpath 'com.android.tools.build:gradle:3.5.1'
classpath'com.google.gms:google-services:4.3.2'
in project gradle and google plugin in app gradle file.
Then add the following dependencies:
implementation 'com.google.firebase:firebase-core:17.2.0'
implementation 'com.google.firebase:firebase-messaging:19.0.0'
You need to create a service of FCM to recieve notifications.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private NotificationManager notificationManager;
private static final String ADMIN_CHANNEL_ID = "CHANNEL_ID";
#Override
public void onNewToken(String s) {
super.onNewToken( s );
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived( remoteMessage );
Map<String, String> data = remoteMessage.getData();
String body = data.get("body");
String title = data.get("title");
String image = data.get("image");
notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels( title, body );
}
Log.d( "Notification", "onMessageReceived: " + image);
Intent notificationIntent = new Intent(this, NotificationActivity.class);
notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP );
PendingIntent pendingIntent = PendingIntent.getService( this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT );
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( this, ADMIN_CHANNEL_ID )
.setSmallIcon( R.drawable.ic_launcher_background )
.setContentTitle( remoteMessage.getNotification( ).getTitle( ) )
.setContentText( remoteMessage.getNotification( ).getBody( ) )
.setContentIntent( pendingIntent );
NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
notificationManager.notify( 0, notificationBuilder.build( ) );
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(String adminChannelName, String adminChannelDescription) {
NotificationChannel adminChannel;
adminChannel = new NotificationChannel( ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW );
adminChannel.setDescription( adminChannelDescription );
adminChannel.enableLights( true );
adminChannel.setLightColor( Color.RED );
adminChannel.enableVibration( true );
if (notificationManager != null) {
notificationManager.createNotificationChannel( adminChannel );
}
}
}
And add this code to your manifest:
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
There are several steps for achieving the notification when application is in background.
You need to use POST parameter in Android FCM service.
You need to code down the thing inside onMessageReceived() from FCM dependencies.
https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages
because i just send notification without message body
i tried solution i just found that i forget this gradle library
implementation 'com.google.firebase:firebase-messaging:20.0.0'
I'm developing an application for Android and iOS and I'm using PushSharp (on server-side) to send push notifications to both platform. In particular I'm using (for Android) the Firebase platform (FCM).
Following this guide I was able to send push notification to an Android device setting icon and sound too but I think there is a problem.
When the notification arrives it doesn't being shown as Heads-up notification but only as status bar notification.
To be clear, I would:
but i see only the application icon that appears on the status bar.
How can I tell to FCM to show my notification as Head-Up notification similary to what I obtain with the following code?
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_media_play)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH);
I have fixed it by installing following version of react-native-push-notification
npm install zo0r/react-native-push-notification.git
in your index.android.js
function init(){
PushNotification.configure({
onNotification:async (notification)=>{
if(!notification.userInteraction && !notification.foreground){
PushNotification.localNotification({
message: "you message"
});
}
,
requestPermissions:true,
senderID:"31************",
popInitialNotification:false
})
}
you must create a channel in your MainActivity.java.
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.os.Build;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ NotificationChannel notificationChannel = new
+ NotificationChannel("500", "MainChannel",
+ NotificationManager.IMPORTANCE_HIGH);
+ notificationChannel.setShowBadge(true);
+ notificationChannel.setDescription("Test Notifications");
+ notificationChannel.enableVibration(true);
+ notificationChannel.enableLights(true);
+ notificationChannel.setVibrationPattern(new long[]{400, 200, 400});
+ NotificationManager manager = getSystemService(NotificationManager.class);
+ manager.createNotificationChannel(notificationChannel);
+ }
Add the channelId to your server: an example with node.js
await admin
.messaging()
.send({
android: {
priority: 'high',
notification: {
sound: 'default',
title: 'your title',
body: 'your message',
imageUrl: 'img-uri',
priority: 'high', // this is importnat
channelId: '500', // the channelId we created in MainActivity.java
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
'apns-push-type': 'background',
'apns-priority': '5',
'apns-topic': '', // your app bundle identifier
},
},
topic: //topic or token,
data: {//send a custom data here to your client},
notification: {
title: 'your title',
body:'your message',
imageUrl: 'img-url',
},