How can I make the firebase notification that arrives while the screen is off emit the sound I have in my raw folder. (if the app is in the foreground the sound runs without problem)
How can I make the firebase notification that arrives while the screen is off emit the sound I have in my raw folder. (if the app is in the foreground the sound runs without problem)
Create the MyService class
public class MyService extends Service {
MediaPlayer mediaPlayer;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return super.onStartCommand(intent,flags,startId);
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.uefa);
}}
In the manifest.xml add
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
In the MyFireBaseMessagingService class add
public void onCreate() {
super.onCreate();
startService(new Intent(getApplicationContext(),MyService.class));
}
This way when a message arrives a sound is played alerting that a message arrived although the phone is with the screen off / close the app
When you send the notification go to advanced options and enable priority and sound:
Remember to assign the sound to the Builder, if the sound is defined on the payload
"sound" : "default"
how to assign a sound stored in the /raw
directory is as follows:
mBuilder.setSound(Uri.parse("android.resource://"+ getPackageName() + "/" + R.raw.mysound));
Ensure that the payload comes from the value of the sound with which you can also determine whether or not to reproduce the sound:
sound (Optional) Indicates a sound for Play when the device receives the notification. Supports default or the name of file of a sound resource contained in the app.
Android sound files must reside in / res / raw /, while that iOS sound files can be found in the content of the client's app or in the Library / Sounds folder of the data container of the app. For more information, see the library for iOS developers.
The documentation indicates that you should use this method:
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark",
"icon" : "myicon",
"sound" : "mySound"
}
}
and define your sound in "sound"
, if you wanted to use one by default it would be enough to put "sound": "default"