简体   繁体   English

延迟重复通知声音

[英]Repeating notification sound with delay

I am attempting to play a notification sound once every two seconds. 我试图每两秒播放一次通知声音。 My code is as follows: 我的代码如下:

final Handler myHandler = new Handler();
mMediaPlayer = new MediaPlayer();

final Runnable mMyRunnable = new Runnable()
{
    @Override
    public void run()
    {
        try 
        {
            mMediaPlayer.setDataSource(getBaseContext(), getAlarmUri(alarm_number));
            final AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
            {
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            }
        } 
        catch (IOException e) 
        {
        }
    }
 };


    mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
    {
        @Override
        public void onCompletion(MediaPlayer mp) 
        {
            myHandler.postDelayed(mMyRunnable, 2000);
        }   
    });

    myHandler.post(mMyRunnable);

When the code executes, the notification sound plays once and then I get an IllegalStateException at the line mMediaPlayer.setDataSource(... I have no idea why. 当代码执行时,通知声音播放一次,然后我在mMediaPlayer.setDataSource(...行获得IllegalStateException mMediaPlayer.setDataSource(...我不明白为什么。

NO! 没有! You should use a Timer which will execute a TimerTask for a repeat rate that you choose: 您应该使用一个Timer ,它将执行TimerTask以获得您选择的重复率:

    Timer timer = new Timer();
    TimerTask task = new TimerTask()
    {
        @Override
        public void run()
        {
            // Do your work here
        }
    };

    timer.schedule(task, 'DELAY_FOR_EXECUTION', 'TIME_TO_WAIT');
example:
   `//timer.schedule(task, 0, 5000);`

This will run immediatly, every 5 secs 这将立即运行,每5秒一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM