Do it in the service:
public class MyService extends Service { @Override public void onCreate() { super.onCreate(); final BroadcastReceiver vReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) {
Then register the BroadcastReceiver with the Intent.ACTION_SCREEN_OFF action to continuously produce a silent sound when the screen is off, and the Intent.ACTION_SCREEN_ON action to stop the music when the screen is on. The volume buttons are active only when playing music.
source share