如何停止音乐背景服务?

时间:2014-12-29 08:52:23

标签: android

我需要一种不断播放活动的背景音乐。我想在点击主页按钮时停止我的背景音乐。

这是我的服务代码。

public class BackgroundSoundService extends Service
{ 

private static final String TAG = null;

MediaPlayer player;

Context context;
private int length = 0;

public IBinder onBind(Intent arg0) {
              return null;   
}

@Override
public void onCreate() {
    super.onCreate();
    player = MediaPlayer.create(this, R.raw.haha);
    player.setLooping(true); // Set looping
    player.setVolume(100,100);



}
public int onStartCommand(Intent intent, int flags, int startId) {
    player.start();
    return 1;

}
 @Override
  public void onStart(Intent intent, int startId) {

   player.start();

  }

  public IBinder onUnBind(Intent arg0) {

  return null;
}

public void onStop() {
    player.stop();
    player.release();
    player = null;
}
public void onPause() {

    player.pause();

        }

public void onHomePressed(){
    player.stop();

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

    }
}

public void resumeMusic()
{
    if(player.isPlaying()==false)
    {
        player.seekTo(length);
        player.start();
    }
}
@Override
public void onDestroy() {
    super.onDestroy();
    if(player != null)
    {
    try{
     player.stop();
     player.release();
        }finally {
            player = null;
        }
    }
}

@Override
public void onLowMemory() {


}

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

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

这是我的第一个活动类

 public class AdventureTime extends Activity implements OnClickListener {


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.story);


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

    View story1 = this.findViewById(R.id.button1);
    story1.setOnClickListener(this);

    View story2 = this.findViewById(R.id.button2);
    story2.setOnClickListener(this);

    View story3 = this.findViewById(R.id.button3);
    story3.setOnClickListener(this);

    View back= this.findViewById(R.id.buttonback);
    back.setOnClickListener(this);

}
            @Override
            public void onBackPressed(){

              new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
              .setMessage("Are you sure you want to exit?")
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                       @Override
                                       public void onClick(DialogInterface dialog, int which) {
                                          Intent intent = new Intent(Intent.ACTION_MAIN);
                                          intent.addCategory(Intent.CATEGORY_HOME);
                                          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                          startActivity(intent);
                                          System.exit(0);

                                       }
             }).setNegativeButton("No", null).show();
            }  

public void onClick(View v) {

    switch(v.getId()){
    case R.id.button1:
        Intent button1 = new Intent(this, Story1.class);
        startActivity(button1);
        break;

    case R.id.button2:
        Intent button2 = new Intent(this, Story2.class);
        startActivity(button2);
        break;

    case R.id.button3:
        Intent button3 = new Intent(this, Story3.class);
        startActivity(button3);
        break;

    case R.id.buttonback:
        Intent buttonback = new Intent(this, MainActivity.class);
        startActivity(buttonback);
        break;


    }     
 }
}

4 个答案:

答案 0 :(得分:0)

在活动AdventureTime中添加:

...
@Override
public void onPause(){
    stopService(svc);
    super.onPause();

}
...

答案 1 :(得分:0)

如果您想在不停止服务的情况下暂停音乐 试试这个 在您的服务中添加此类

public class LocalBinder extends Binder {
    BackgroundSoundService getService() {
        return BackgroundSoundService.this;
    }
}

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

private final IBinder mBinder = new LocalBinder();

并在您的活动中添加此内容

private BackgroundSoundService mBoundService;

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        mBoundService = ((BackgroundSoundService.LocalBinder)service).getService();

    }

    public void onServiceDisconnected(ComponentName className) {

        mBoundService = null;

    }
};

替换

    startService(svc) 

    bindService(svc, mConnection, Context.BIND_AUTO_CREATE);

并在需要时调用暂停方法

mBoundService.pauseMusic();

答案 2 :(得分:0)

为什么不尝试收听dispatchKeyEvent呢?你可以写:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
        stopService(svc)
        return true;
    }
    else
        return super.dispatchKeyEvent(event);
  }

您的每项活动。

答案 3 :(得分:0)

你在mainActivity类上添加了这个。

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
// pause or stop ung Background music here.
            return true;
        }
        return false;
    }