简体   繁体   中英

Notification sound when service ends

I have a service that when it finishs running tasks it plays a notification with sound. As it ends, my calling application, if it is on top calls to stopservice. The problem is that notificationmanager returns before the sound ends, so the application stops the service before the sound has finished (if it is long). Is there a way I can detect when the sound has finish in order to not let the service stops before the sound ends?. I have been looking into soundmanager and other threads without luck. Also, A workaround is to put a Thread.sleep(ms), but if the notificatio sound is long, it could be stopped anyway, and I would like responsitivity from my app just after service finishs. A possible solution would be to calculate the length of the mp3 file but I dont know how to do it....

Assuming you are using a MediaPlayer for playback, you can get the duration with MediaPlayer.getDuration() .

Please note, that this won't work with some VBR mp3. so you might want to save the mp3 with a constant bitrate or run a tool like vbrfix before putting them in your app.

The duration is returned in milliseconds, so you can simply pass this value to SystemClock.sleep()

/edit:

Okay, if you have the file saved as an asset, you can use this code:

MediaPlayer media = new MediaPlayer();
    AssetFileDescriptor descriptor;
    try {
        descriptor = assetMan.openFd("YOURNAME.mp3");
        media.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();
        media.prepare();
    } catch (IOException e) {
        // File not found
        e.printStackTrace();
    }
     media.getDuration();
    media.release();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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