2

i created a android app game that has a welcome screen named MainActivity.class and will intent in Maimenu.class after 5 sec of sleep. the MainMenu class has start game,settings,about, and high score function. but my problem is i dont know how to make my background music play in all my activities/class it only plays in my welcome screen. i want that the background music will play continously in all my activity/class. 2nd problem is ihave a button ON and OFF in my settings class. how can i turn OFF my background music if i click the button off in my Settings.class. hope you can help me :) i appreciate your time answering my problem.god bless. btw newbie here

public class MainActivity extends Activity  {

MediaPlayer backgroundmusic;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MediaPlayer backgroundmusic = MediaPlayer.create(MainActivity.this, R.raw.bsound);
    backgroundmusic.start();
    Thread timer = new Thread(){

        public  void run(){
            try {
            sleep(5000);

            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{
                Intent intent = new Intent(getApplicationContext(),MainMenu.class);
                startActivity(intent);
            }
        }
    };
    timer.start();
}
user2630787
  • 65
  • 1
  • 8

1 Answers1

6

You can use below code

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MusicService extends Service  implements MediaPlayer.OnErrorListener{

private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;

public MusicService() { }

public class ServiceBinder extends Binder {
     MusicService getService()
     {
        return MusicService.this;
     }
}

@Override
public IBinder onBind(Intent arg0){return mBinder;}

@Override
public void onCreate (){
  super.onCreate();

   mPlayer = MediaPlayer.create(this, R.raw.jingle);
   mPlayer.setOnErrorListener(this);

   if(mPlayer!= null)
    {
        mPlayer.setLooping(true);
        mPlayer.setVolume(100,100);
    }


    mPlayer.setOnErrorListener(new OnErrorListener() {

  public boolean onError(MediaPlayer mp, int what, int
      extra){

        onError(mPlayer, what, extra);
        return true;
    }
      });
}

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

public void pauseMusic()
{
    if(mPlayer.isPlaying())
    {
        mPlayer.pause();
        length=mPlayer.getCurrentPosition();

    }
}

public void resumeMusic()
{
    if(mPlayer.isPlaying()==false)
    {
        mPlayer.seekTo(length);
        mPlayer.start();
    }
}

public void stopMusic()
{
    mPlayer.stop();
    mPlayer.release();
    mPlayer = null;
}

@Override
public void onDestroy ()
{
    super.onDestroy();
    if(mPlayer != null)
    {
    try{
     mPlayer.stop();
     mPlayer.release();
        }finally {
            mPlayer = null;
        }
    }
}

public boolean onError(MediaPlayer mp, int what, int extra) {

    Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
    if(mPlayer != null)
    {
        try{
            mPlayer.stop();
            mPlayer.release();
        }finally {
            mPlayer = null;
        }
    }
    return false;
}

Binding the Activity to the Service

private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){

public void onServiceConnected(ComponentName name, IBinder
 binder) {
mServ = ((MusicService.ServiceBinderbinder).getService();
}

public void onServiceDisconnected(ComponentName name) {
    mServ = null;
}
};

void doBindService(){
    bindService(new Intent(this,MusicService.class),
            Scon,Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

void doUnbindService()
{
    if(mIsBound)
    {
        unbindService(Scon);
        mIsBound = false;
    }
}

Starting, Pausing, Resuming and Stopping the Music Follow the given steps:

Step 1: First bind the service to the activity by calling doBindService on your activity's onCreate as passing an intent to the service.

Step 2: Start the service by an explicit Intent:

Intent music = new Intent();
music.setClass(this,MusicService.class);
startService(music);

Step 3: From your activity, wherever you want to pause, resume or stop music, call the corresponding service functions as follows:

mServ.pauseMusic();
mServ.resumeMusic();
mServ.stopMusic();

Step 4: Don't forget to call doUnbindService from places where you want to unbind the service from the activity. An ideal place is the call to activity's onDestroy()method.

Step 5: In your application's androidmanifest file, paste the following XML code:

< service android:name=".MusicService" android:enabled="true" / >
NoWar
  • 36,338
  • 80
  • 323
  • 498
Kirtikumar A.
  • 4,140
  • 43
  • 43