On onReceive method when i get a new message, after i do some checkups and see that the address number is the one i want.
Is it possible to play my notification sound instead of the default message sound? And if a normal message comes then the default sound will play.
The thing is that the phone plays the sound first, and then my application, so there is a conflict there.
Ive searched for an answer but i couldnt find anything.
What i do is kind of unefficient. I play my sound 6 seconds after the default notifications plays like this:
private Runnable task = new Runnable() {
public void run() {
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone r = RingtoneManager.getRingtone(
getApplicationContext(), alarmSound);
r.play();
}
};
private void delayNotification() {
Handler handler = new Handler();
int millisDelay = 6000;
handler.postDelayed(task, millisDelay);
}
I know its not a good way to do it so thats y i came here:P
notification.sound =Uri.parse("android.resource://"+context.getPackageName()+"/"
+R.raw.tone);
Related
I'm trying to implement a custom notification sound in my application.
I have written the following code, but the application plays only default sound and not the custom sound i've added in raw folder. Upon receiving the notification, the logs doesn't even throw any error or exception as to why it isn't playing the custom sound. I tried searching online and tried following different approaches but to no avail.
Please let me know where am i going wrong.
Edit: Can someone post the code for it, i cant seem to find anything that works
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.notify);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MyCuS Notification", "My Notification", NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = getSystemService(NotificationManager.class);
AudioAttributes.Builder audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE);
channel.setSound(Uri.parse("android.resources://" + getPackageName() + "/" + R.raw.bg_reminder_alarm),audioAttributes.build());
manager.createNotificationChannel(channel);
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, "MyCuS Notification");
builder.setContentTitle("MyTitle");
builder.setContentText("TESTING");
builder.setSmallIcon(R.drawable.ic_launcher_background);
builder.setAutoCancel(true);
builder.setSound(Uri.parse("android.resources://" + getPackageName() + "/" + R.raw.bg_reminder_alarm));
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(MainActivity.this);
managerCompat.notify(1, builder.build());
}
});
}
Edit 2: I tried deleting existing channel and sending notification to create new channel, when newly created the description of the channel changes after sending second notification, it is as if the channel is overridden or deleted and new default channel is created.
Since Android Oreo / 8 the Notificationsound is coming from the Channel and can only be set the first time you add the channel via your channel.setSound().
If you want to change it later on you need to delete the channel and then re-add it to the system. The user will be warned about that behaviour though (App deleted channels X amount of times).
https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels
If you want to have a customsound each and every time, you need a ForegroundService without a channelsound for it's foreground notification (setSound(null)) and then use the MediaPlayer on the Notificationstream to play the custom sound.
I'm developing ,for educational purposes, a Android APP.
This APP have a GCMService and works well, but I'm trying to start a simple sound or alarm when the APP receive a certain message from GCM Service.
How I can do this?
I'm searching for information, but always see the people start a Service or Activity, and I think this is much easy.
Thanks ALL!
You can write the code into onMessage() of GCMIntentService like
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = getString(R.string.gcm_message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
//Write here for sound notification
//for example
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringer = RingtoneManager.getRingtone(getApplicationContext(), notification);
ringer.play();
}
start a simple sound or alarm when the APP receive a certain message
from GCM Service
You can put condition in above method and play soound. like
if ("XYZ".equals(message)) {
//Then Play a sound
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringer = RingtoneManager.getRingtone(getApplicationContext(), notification);
ringer.play();
}
I have an Android app that plays a notification ringtone (RingtoneManager.TYPE_NOTIFICATION) when certain events are sent to a BroadcastReceiver.
The code that plays the ringtone basically does:
onReceive(Context context, Intent intent)
{
...
Uri ringtoneUri = someFunctionToLookupAValidNotificationRingtoneUri();
...
Ringtone tone = RingtoneManager.getRingtone(context, uri);
Log.v(TAG, "About to play ringtone");
tone.play();
}
Every so often when this code is run, the ringtone starts playing over and over again infinitely. Sometimes it happens when a large number of events are bunched close together, but it has also happened when only one event came in. The log message (and debugging) verifies that the tone.play() call is happening only once per event, and there isn't an infinite stream of events.
The only way stop the infinite looping is to kill my app.
It's almost as if every so often, Android forgets to flush the sound output buffer and so it keeps looping through playing whatever is inside.
Any ideas how to debug and/or fix this issue?
I had a similar problem. It turned out that when a ringtone is played, it will repeat indefinitely until stopped, whereas when a notification sound is played, it will play only once. So my guess is that the difference in your case lies in whether a ringtone or a notification sound was selected in someFunctionToLookupAValidNotificationRingtoneUri(). As you do not supply the code for someFunctionToLookupAValidNotificationRingtoneUri(), I cannot know what happens there.
Picking a notification sound
If you use a ringtone picker for the user to select a notification sound, this code will start the intent to pick a notification sound as opposed to a ringtone:
private void PickANotificationSound() {
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
// We want a notification sound picked. If we don't add this to the
// intent, a ringtone is picked; this means that when it is played,
// it will keep on playing until it is explicitly stopped. A
// notification sound, however, plays only once.
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
RingtoneManager.TYPE_NOTIFICATION);
// Start the intent to pick a notification sound. The result will show
// up later when onActivityResult() is called.
startActivityForResult(intent, REQUESTCODE_NOTIFICATION_SOUND);
}
where REQUESTCODE_NOTIFICATION_SOUND is just a local constant with any name and value, identifying the request:
private static final int REQUESTCODE_NOTIFICATION_SOUND = 1;
An onActivityResult() callback function like this will then pick up the notification sound URI and play it:
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == REQUESTCODE_NOTIFICATION_SOUND) {
try {
if (resultCode == RESULT_OK) {
Uri ringtoneUri = data.getParcelableExtra(
RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (ringtoneUri != null) {
PlayRingtoneOrNotificationSoundFromUri(ringtoneUri);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else
super.onActivityResult(requestCode, resultCode, data);
}
private void PlayRingtoneOrNotificationSoundFromUri(Uri ringtoneUri) {
Ringtone ringtone = RingtoneManager.getRingtone(
getApplicationContext(), ringtoneUri);
if (ringtone != null) {
ringtone.play();
}
}
Because we said in the intent that we wanted to pick a notification sound, the resulting sound is a notification sound and is therefore only played once after the call to ringtone.play().
If we had said in the intent that we wanted to pick a ringtone, like this:
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
RingtoneManager.TYPE_RINGTONE);
the picker would return a ringtone that would play indefinitely after the ringtone.play() call – until stopped by ringtone.stop() or the application was killed.
Two meanings of 'ringtone'
Note that the terminology in the Android API adds to the confusion, as the word "ringtone" is used with two different meanings (cf. the documentation of RingtoneManager):
Any sound meant to catch the user's attention, such as a sound to play repeatedly when the phone rings, a notification sound, or a similar sound. This meaning is used in the name RingtoneManager.
A sound to play repeatedly when the phone rings, as opposed to a notification sound or a similar sound. This meaning is used in the name TYPE_RINGTONE in RingtoneManager.TYPE_RINGTONE.
I have this method in my main activity
private void beep()
{
AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
manager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0,
AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
r.play();
}
As I understand, notification sound volume should be regulated by STREAM_NOTIFICATION. But notification always plays with the same volume despite that volume number in setStreamVolume method. Why is that?
I went another way. It's not exactly answer to my question but appropriate one. When I play notification in STREAM_MUSIC everything is fine. So notification plays exactly with volume I pass as parameter to the function
private void beep(int volume)
{
AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
manager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer player = MediaPlayer.create(getApplicationContext(), notification);
player.start();
}
First of all, I hope you realize that you are attempting to play two notifications right after each other, so there might be a conflict about that. AudioManager.FLAG_PLAY_SOUND and r.play() will both try playing the sound. It is usually enough to give user one type of information, either by UI or by playing the beep with new volume. I suggest you delete one of the flags. If you don't need any, just give it 0.
Coming to the main question, I am not sure if you can set volume level to 0. Try putting 1, like
manager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, 1, AudioManager.FLAG_SHOW_UI);
If you want to mute the notification, try using setStreamMute, which is equivalent to setting the volume to 0.
For my case eventually this seemed to be working.
It would make your audio volume relative to the stream current volume but it was useful for my need.
MediaPlayer player = MediaPlayer.create(getApplicationContext(), notificationUri);
player.setVolume(toneLevel, toneLevel);
toneLevel is between 0.0 - 1.0 so you don't even need to find the range of your stream..
Write a function as follow, or copy and paste the following,
public void ringtone() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {}
}
and call ringtone() when you want to make a beep notification.
I need to play a ringtone from a application which I am able to achieve. Now, I want to play the ringtone only for the specific duration based on the user input.
If user selects 60sec, the audio should play 60sec only and then stop.
Is there any way to achieve this?
Cheers,
Prateek
Yes, timertask works well for this. Here's the code I use and it works:
long ringDelay = 3500;
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
final Ringtone alarmRingtone = RingtoneManager
.getRingtone(getApplicationContext(), notification);
alarmRingtone.play();
TimerTask task = new TimerTask() {
#Override
public void run() {
alarmRingtone.stop();
}
};
Timer timer = new Timer();
timer.schedule(task, ringDelay);
Of course. Use TimerTask to stop playback after the given period of time.