0

我有一个类扩展了播放我的应用程序背景音乐的服务管理器。当您退出应用程序时,服务会完全停止,但是当您使用 Home 按钮退出应用程序时,背景音乐会停止,但后者会恢复而不返回应用程序。会是什么?

谢谢。

我的服务:

public class MusicManager extends Service  implements MediaPlayer.OnErrorListener{

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

String[] myMusic = {"mfx/Track01.ogg", "mfx/Track02.ogg", "mfx/Track03.ogg"};        
private static int mUltimaPista = -1;

public MusicManager() { }

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

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

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

//Musica
  SiguienteCancion();        
  MusicFactory.setAssetBasePath("mfx/");
  AssetFileDescriptor afd = null;       
  try {
    afd = getAssets().openFd(myMusic[mUltimaPista]);
    mPlayer = new MediaPlayer();
    mPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
        afd.close();
        mPlayer.prepare();
    } catch (IllegalArgumentException e) {
        Log.d("Kids",e.getMessage());
    } catch (IllegalStateException e) { 
        Log.d("Kids",e.getMessage());           
    } catch (IOException e) {
        Log.d("Kids",e.getMessage());
    }        

  mPlayer.setOnCompletionListener(new OnCompletionListener() {            
      public void onCompletion(MediaPlayer mp) {
          mp.reset();
          mp.setVolume(0.25f, 0.25f);
          try {
            SiguienteCancion();
            MusicFactory.setAssetBasePath("mfx/");                   
              AssetFileDescriptor afd = getAssets().openFd(myMusic[mUltimaPista]);
              if (afd != null) {
                  mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                  afd.close();
                  mp.prepare();
                  mp.setVolume(0.25f, 0.25f);
                  mp.start();
              }
          } catch (Exception ex) {
              // report a crash
            Log.d("Kids",ex.getMessage());
          }
      }
  });       

    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.reset();        
     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;
}

// Obtenemos la siguiente canción a reproducir
public void SiguienteCancion()
{
    Random rand = new Random();
    int track = Math.abs(rand.nextInt() % 3);

    while (track == mUltimaPista)
    {
        track = Math.abs(rand.nextInt() % 3);
    }               

    mUltimaPista = track;
}

}

主要活动:

private boolean mIsBound = false;
private MusicManager mServ;
private ServiceConnection Scon =new ServiceConnection()
{
    public void onServiceConnected(ComponentName name, IBinder service) {                       
        mServ = (MusicManager)((ServiceBinder) service).getService();
    }

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

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

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

public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback)
        throws Exception {                                                            
    Intent music = new Intent();
    music.setClass(this,MusicManager.class);
    startService(music);

    doBindService();

    pOnCreateResourcesCallback.onCreateResourcesFinished();
}
@Override
public void onResumeGame() {
    super.onResumeGame();

    if (mServ != null)
    {                   
        mServ.resumeMusic();                        
    }                                         
}
@Override
public void onPauseGame() {
    if (mServ != null)
    {           
        mServ.pauseMusic();
    }

    super.onPauseGame();                                                        
}

其他活动:

private boolean mIsBound = false;
private MusicManager mServ;
private ServiceConnection Scon =new ServiceConnection()
{
    public void onServiceConnected(ComponentName name, IBinder service) {                       
        mServ = (MusicManager)((ServiceBinder) service).getService();
    }

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

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

void doUnbindService()
{
    if(mIsBound)
    {
        unbindService(Scon);
        mIsBound = false;
    }
}
public void onCreateResources(
        OnCreateResourcesCallback pOnCreateResourcesCallback)
        throws Exception {

    doBindService();

    pOnCreateResourcesCallback.onCreateResourcesFinished();

}
 @Override
public void onResumeGame() {
    super.onResumeGame();

    if (mServ != null)
    {           
        mServ.resumeMusic();                        
    }
}

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

    if (mServ != null)
    {
        mServ.pauseMusic();
    }               
}
4

1 回答 1

0

在您的主要活动中,将代码放在下面。

@Override
protected void onResume() {
    if (!SoundService.isMediaPlaying()) {
            startService(new Intent(Game.this, SoundService.class));
    }
}

@Override
protected void onPause() {
    stopService(new Intent(this, SoundService.class));
}

还添加以下功能您的服务。

public static boolean isMediaPlaying() {
    if (bgMusic != null) {
        try {
            return bgMusic.isPlaying();
        } catch (Exception e) {
        }
    }

    return false;
}

如果处理您的游戏的所有活动,则此活动的所有代码然后在恢复和暂停方法上设置布尔变量

于 2013-04-02T07:44:16.110 回答