'Android Studio media player doesnt play when the app is closed

I made an Android app that should play a sound when event is received, it works when app is in focus, but when the app is closed/collapsed sound doesnt play, only standard notification. How to start a sound/music that is placed inside the app when app with the foreground service?

Main activity:

public class MainActivity extends AppCompatActivity {
    private Intent alarmServiceIntent;
    private ServiceConnection sConn;
    private boolean bound;
    private boolean alarm = false;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Init();
    }

    private void Init() {
        alarmServiceIntent = new Intent(this, AlarmService.class);
        sConn = new ServiceConnection() {
            public void onServiceConnected(ComponentName name, IBinder binder) {
                bound = true;
            }
            public void onServiceDisconnected(ComponentName name) {
                bound = false;
            }
        };
        ContextCompat.startForegroundService(this, alarmServiceIntent);
    }
    private void playAlarm() {
        bindService(alarmServiceIntent, sConn, BIND_AUTO_CREATE);
    }
   
    public void stopAlarm(View v) {
        if (sConn != null ) {
            unbindService(sConn);
        }
        if(alarmServiceIntent != null) {
            stopService(alarmServiceIntent);
        }
    }
   //here is the method to receive event and call playAlarm
}

Alarm service:

public class AlarmService extends Service{
    private final String CHANNEL_ID = "ID";
    private final String CHANNEL_NAME = "NAME";
    private IBinder mBinder = new MyBinder();
    private MediaPlayer player;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        play();
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        onStop();
        return super.onUnbind(intent);
    }
    
    @Override
    public void onCreate() {
        player = MediaPlayer.create(this,R.raw.alarm);
        player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = null;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity
                    (this, 0, notificationIntent, PendingIntent.FLAG_MUTABLE);
        }
        else
        {
            pendingIntent = PendingIntent.getActivity
                    (this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
        }

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("TITLE")
                .setSmallIcon(R.mipmap.icon)
                .setContentIntent(pendingIntent)
                .build();
        NotificationManager  mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager.createNotificationChannel(channel);
            new NotificationCompat.Builder(this, CHANNEL_ID);
        }
        startForeground(619, notification);

        return START_REDELIVER_INTENT;
    }


    public void play() {
        if(player == null) {
            player = MediaPlayer.create(this,R.raw.alarm);
            player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        }
        Log.v("ALARM", "play: 12345");
        player.setAudioAttributes(
                new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build()
        );
        player.setVolume(2,2);
        AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        // audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
        player.setLooping(true);
        player.start();

    }
    class MyBinder extends Binder {
        AlarmService getService(){
            return AlarmService.this;
        }
    }
}


Solution 1:[1]

You should override onDestroy method and call stop there.

@Override
public void onDestroy() {
    player.stop();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Em Ae