How can I keep running an activity when screen is off or locked in Android studio in Java?

I am developing an App, which can play a tone at a fixed frequency to the users by using the Audiotrack Java class. Now the sound can be played when a button is pressed, I want to keep the sound keep playing when the screen is off, because the users may want to listen to the sound for 20 minutes at night where doesn't require the screen on all the time. Anyone can help with this?

I have tried the WakeLock according to other posts on Stack overflow, but it doesn't work. when I go to the activity, the app stops and quits.


To keep sound playing when the screen is off, use a foreground service to play the sound and when the user clicks the start button, you should start your service