How to handle Alarm notification in Android? - android

I'm developing an media player application for Android, for which I need to handle any Alarm notification, and based on that I'll pause my playback. When the Alarm in snoozed or dismissed, I'll then resume the playback.
I googled a lot for the Alarm handling, but what I found was the way to enable Alarm notifications through code, set the intent and then handle it. However, no where could I locate just handling the Alarm notification part. I don't need to set the Alarm on, it could've been set by the user, and I don't need to programmatically. All I need is just handle that notification.
Any ideas on this would be extremely useful?
Thanks,
Asheesh

HI Asheesh Vashishtha,
Correct me on this, but AFAIK whenever any other application even if it is the alarm clock, is activated, your activity will surely go in background. So i guess u can override the OnPause and OnResume functions to put your bit of code. As far as snooze or other things are concerned, they all will result in the Alarm Activity getting destroyed(or paused, don know much about it) and your activity will get resumed. So that wont be a matter of concern for u!
Hope this helps...

AFAIK, there is no way for you to be notified of what the Alarm Clock application does, any more than you get notified about any other third-party alarm clock.
Note that AlarmManager -- what you were probably reading about -- is not the same as the Alarm Clock application.
Sorry!

I ran into a similar situation while developing a media player. My solution was to use the AudioManager's OnAudioFocusChangeListener.
You implement the listener in the class like so
public class VideoPlayerHelper implements AudioManager.OnAudioFocusChangeListener {
Then you override onAudioFocusChange
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
//Just fall through by omitting break
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
LogUtil.log(LogUtil.DEBUG, TAG, "AUDIOFOCUS_LOSS or AUDIOFOCUS_LOSS_TRANSIENT"); //Custom logging class
if (isPlaying()) {
pause();
mAudioManager.abandonAudioFocus(VideoPlayerHelper.this);
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
LogUtil.log(LogUtil.DEBUG, TAG, "AUDIOFOCUS_GAIN"); //Custom logging class
break;
default:
break;
}
}
The key here is AudioManager.AUDIOFOCUS_LOSS_TRANSIENT. This was the code the listener kept receiving when the alarm clock would go off (on The Note 5). So I simply handled AudioManager.AUDIOFOCUS_LOSS_TRANSIENT the same as AudioManager.AUDIOFOCUS_LOSS by pausing the media player and letting go of the audio focus.
When we setup the media player, I added this line before adding the data source
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Make sure your code for starting the media player also has this line in it (I have it in the start code and onResume code in case the alarm went off while the app was in the background).
mAudioManager.requestAudioFocus(VideoPlayerHelper.this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
That line helps you get back the audio focus when you hit the play button after dismissing the alarm clock.
You should also let go off audio focus when you're finished with the media player. I put this line of code in the onStop and onDetach methods.
mAudioManager.abandonAudioFocus(VideoPlayerHelper.this);
It's not as much setup as you may think and it allows you to adjust your media player whenever unexpected audio is introduced (such as an alarm clock or timer goes off).

Related

Make ExoPlayer seek to last point in time whenever play is pressed from the notification?

The application streams audio from a server using ExoPlayer, I have an issue of streaming clients falling behind when they pause and play again. I need for the stream to be caught up every time playing is resumed. All this from the notification controls.
I've got it working inside the app with seekTo(0) but apparently the notification control calls are different.
fun play() {
player?.playWhenReady = true
player?.seekTo(0)
}
fun pause() {
player?.playWhenReady = false
}
Is there anywhere to access whatever the notification controls are calling and maybe modify them?
I think PlayerNotificationManager class might help you,Once attached the manager will keep it sync with player so it might help in your case.
You can have a look at this blog it might help:
https://medium.com/google-exoplayer/playback-notifications-with-exoplayer-a2f1a18cf93b

Android service timer

Can an audio service be set to a timer? Example would be for a sleep machine type app where the user clicks the time they want the sound to play and then the sound plays for that time. I was told that using a service to handle the audio was the proper way but I do not know how to get it to work with a timer for a user selected input
Short answer, yes it is possible.
I have done audio recording using a background service, have also done FTP downloads in a background service.
You would use a started service in this case, it will play audio using following:
http://developer.android.com/reference/android/media/MediaPlayer.html
You may pass a value from Activity to Service using intent extras, for example
Intent intService = new Intent(AndroidSignageActivity.this, SignageDownloadService.class);
intService.putExtra("TIMEVAL_MILLISEC", 1000);//
startService(intService);
In the service, you can extract the value and use it in onStartCommand method as following:
long lTimeout = 0;
if(intent.hasExtra("TIMEVAL_MILLISEC")){
lTimeout = intent.getLongExtra("TIMEVAL_MILLISEC", 100);
}

Best way to handle AudioManager in android

I'm wondering, what is the best way to handle the AudioManager in Android, for media.
As you know, AudiManager manage different type of audio, like music or ringtone.
If I have an applicaiton playing sound effects and vibrating, with 3 activity, how do I have to handle this class ?
-Do I have to set the volume on the onCreate method in each activity ?
Then use it
audioManager.setVolumeControlStream(AudioManager.STREAM_MUSIC);
-Or do I have to make a static reference, and use it each time ?
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
-Or is these wrong, and I didn't understand how it works ?
To tell the truth, I'm having problem handling this im my 3 activities : in the first 2 activities, I have sound effect, and in the 3rd one, only vibration. In the first activity, the sound is in "Ringtone mode", and the other two "Media mode". So the sound volume is different which is bad.
In order to use the AudioManager you have to have an instance of it (in every Activity or Service you want to use it) so:
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
then you can use it:
audioManager.setVolumeControlStream(AudioManager.STREAM_MUSIC);
This doesn't need to be called inside the OnCreate() method but need to be called before you play the sound.

Best way to notify user of an alarm

So, I seem to have fallen down a rabbit hole trying to figure out the best way to notify a user of an alarm going off.
Basically, I want some kind of notification/dialog to come up at a certain time, and it should come up no matter what the user is doing, and block further use until acted upon (dismissed or otherwise).
Right now, I have an AlarmManager, and the BroadcastReceiver that is registered with it starts a new service.
Every time I thought I was heading in the right direction, I hit a problem where someone online had a similar issue, and was told "don't do it that way." (Having a service create/show an AlertDialog, for instance.)
I was hoping someone could give me a brief list of what their recommendation would be; I don't need code (at least I shouldn't), just some high level abstraction.
Go with Notification, which plays a sound perhaps, that would pull your user's attention to your notification, just like the default alarm does.
And make the notification an ongoing one. Which can't be removed by the user, until and unless some action is performed to change the state of the notification.
Android: How to create an "Ongoing" notification?
Dialogs for this situation would be annoying for me. The docs also suggest not to use them in these scenarios.
Have a look at this Sample Open Source Project
I did it in this way and it work fine for me.
Create a class and Call it something like ScheduledService it extends IntentService, in this class you'll do what you want to do when alarm goes off.
public class ScheduledService extends IntentService {
public ScheduledService() {
super("My service");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do something, fire a notification or whatever you want to do here
Log.d("debug", "Ring Rind !");
}
}
then in you activity to start the alarm use the following:
AlarmManager mgr = (AlarmManager) YourActivity.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(YourActivity, ScheduledService.class);
PendingIntent pi = PendingIntent.getService(YourActivity, 0, i, 0);
mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + PERIOD, pi);
Which PERIOD is after how much milliseconds you want the alarm to goes off.
To cancel stop the timer and cancel the alarm use:
if (mgr != null)
mgr.cancel(pi);
Finally for all this to work you need to register your ScheduledService class as a Service.
In your manifest add this tou your application:
<application
... />
...
<service android:name=".ScheduledService" >
</service>
</application>
This way the Android OS will take care of firing the alarm when it's time. even if other application is running or even if your app process is terminated.
Hope this help.
Regards.
Just a crazy idea: Create an activity and set it's theme to be fullscreen with no title bar and a button to stop the alarm maybe, instead of doing a notification just make an intent that starts that activity "maybe you will need This" to work even when phone is locked and play some annoying sounds, "This" may help, when the activity starts. you can also override the onBackPressed() to do nothing.

How to check something at regular intervals?

Beginner here, I have a simple question.
In Android what would be the best what to check for something at regular intervals?
Please bear with me, I'll try to explain the best I can --
For example my audio app is very simple, a main activity and a service. The main activity has a UI with two buttons, start and stop audio. I press start and the audio service starts. Likewise when I click Stop the service stops and the audio ends. If isLooping() is hard-coded to true there is no issue because the audio never ends unless I hit stop button, which stops the audio service and also resets the button states.
This is an issue now because I set isLooping() to false so the audio doesn't loop. So the audio will stop playing but the service is still running.
I want to be able to detect when the audio stops so I can set the states of the UI buttons. So I need something that is always checking whether audio is playing (i.e. check player.isPlaying() so I can end the service and set the enable/disable state of the buttons.
I figured out binding to the service so I can access the MediaPlayer controls via my main activity so I know the code to check if it's playing, but WHERE do I put this code so it's checked all the time?
Am I making sense? I know this is probably very simple. Thanks for any help.
You can repeat it with the TimerTask and Timer. Code below:
public final void RepeatSoundFunction(){
t = new Timer();
tt = new TimerTask() {
#Override
public void run() {
mp.seekTo(0); //Reset sound to beginning position
mp.start(); //Start the sound
t.purge(); //Purge the sound
}
};
t.schedule(tt, 10*1000); //Schedule to run tt (TimerTask) again after 10 seconds
}
then you set a MediaPlayer onCompletionListener and in there you put this.
Inside the run-code you can check for other things than
music, I just show an example with the audio.

Categories

Resources