Search code examples
androidandroid-servicebackground-musicandroid-music-player

Android background music service


I am developing an entertainment app in android. I want to play background music, and I want to use service for that. App have 3 activities and music must be played across all activities. Also, when activity is paused, music must PAUSE and stopped when destroyed. Can anyone tell me how to do this ? any links or examples ?

Thank you.


Solution

  • Do it without service

    https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion

    If you are so serious about doing it with services using mediaplayer

    Intent svc=new Intent(this, BackgroundSoundService.class);
    startService(svc);
    

    public class BackgroundSoundService extends Service {
        private static final String TAG = null;
        MediaPlayer player;
        public IBinder onBind(Intent arg0) {
    
            return null;
        }
        @Override
        public void onCreate() {
            super.onCreate();
            player = MediaPlayer.create(this, R.raw.idil);
            player.setLooping(true); // Set looping
            player.setVolume(100,100);
    
        }
        public int onStartCommand(Intent intent, int flags, int startId) {
            player.start();
            return 1;
        }
    
        public void onStart(Intent intent, int startId) {
            // TO DO
        }
        public IBinder onUnBind(Intent arg0) {
            // TO DO Auto-generated method
            return null;
        }
    
        public void onStop() {
    
        }
        public void onPause() {
    
        }
        @Override
        public void onDestroy() {
            player.stop();
            player.release();
        }
    
        @Override
        public void onLowMemory() {
    
        }
    }
    

    Please call this service in Manifest Make sure there is no space at the end of the .BackgroundSoundService string

    <service android:enabled="true" android:name=".BackgroundSoundService" />