How to stop android notification ringtone after 30 seconds?

前端 未结 3 1918
难免孤独
难免孤独 2021-02-04 12:26

I\'m writing an app that notifies a user of very time sensitive information, and I think a lot of them would want to use a phone ringtone instead of just the short notification

相关标签:
3条回答
  • 2021-02-04 12:46

    An simple workaround would be to cancel the notification after 30 secs and create a new one.

    You could even clone the original Notification and just remove the ring-tone for the new one.

    0 讨论(0)
  • 2021-02-04 12:50

    Android does not give you access to interfere with the notification playing the sound but if you have the full control of the ringtone you are playing, then you can stop it after 30 seconds or do whatever you want with it.

    Here, I am assuming that you are using a background service to execute the notification.

    As a preliminary step, you should make the notification without sound. Just a default, simple taskbar notification. Then, we will use our own MediaPlayer object to play the ringtone for 30 seconds.

    1) IF YOU ARE EXECUTING THE NOTIFICATION ON THE SPOT: Create a MediaPlayer object, start playing the ringtone the user picked right after you start the notification. Then count 30 seconds with a Timer and TimerTask (see example here on how to use them) or ScheduledThreadPoolExecutor and call MediaPlayer stop() to stop the ringtone after 30 seconds.

    2) IF YOU ARE SCHEDULING THE NOTIFICATION FOR A LATER TIME: As soon as you set your notification, create an AlarmManager and schedule it so that it will be triggered at the same time with your notification. Your alarm could trigger another background service that you wrote in which you play the ringtone for 30 seconds using a MediaPlayer object as explained in part 1).

    In both cases, the notification will still be there and the way you will play the ringtone will totally be independent of it. You will have full control over the ringtone. You can even replay it for another 30 seconds after some scheduled time if the user has not checked the notification till that time (since you are saying that the notification delivers a very time sensitive information, otherwise I wouldn't bug the user with ringtones playing insistingly).

    0 讨论(0)
  • 2021-02-04 13:10

    This should do it.

    ....
    mediaPlayer.start();
    ....
    final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer.isPlaying())
                    mediaPlayer.stop();
            }
        }, timeout);
    
    0 讨论(0)
提交回复
热议问题