0

Hello im making a android game application and i want to make a background music for my game. i have found some code here in stackoverflow but its not work properly because when i press the back button or home button the music is still playing, even i remove it from task its still running it mean onPause or onDestroy is not working. can someone help me, thank you!.

here's the link where i found the codes Android background music service

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
jopo
  • 23
  • 5

2 Answers2

0

I think you play music as a service and you must destroy this service in onPause and onDestroy of your activity.

0

1) First put your music.mp3 into raw folder

2) Declaring a service in the manifest as child of the <application> element

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

3) Add MusicService.java class:

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class SoundService extends Service {

MediaPlayer mPlayer;

    @Override
    public void onCreate() {
        mPlayer = MediaPlayer.create(this, R.raw.music); 
        mPlayer.setLooping(true); 
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mPlayer.start();
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mPlayer.stop();
        mPlayer.release();
        super.onDestroy();
    }

}

4) Run\Stop services in the activity:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        startService(new Intent(MainActivity.this, SoundService.class));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onBackPressed() {
        stopService(new Intent(MainActivity.this, SoundService.class));
        super.onBackPressed();    
    }

    @Override
    protected void onPause() {
        // When the app is going to the background
        stopService(new Intent(MainActivity.this, SoundService.class)); 
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // when system temporarily destroying activity 
        stopService(new Intent(MainActivity.this, SoundService.class));
        super.onDestroy();
    }

}
5ec20ab0
  • 742
  • 6
  • 15