android - The same background music playing in all activities -
i use services play background music in activities , works. problem music continues playing if app in background (when user exit home button or button). how can solve this?
services class backgroundsoundservice
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.slow_shock); player.setlooping(true); // set looping player.setvolume(100,100); } public int onstartcommand(intent intent, int flags, int startid) { player.start(); return start_not_sticky; } public void onstart(intent intent, int startid) { // } public ibinder onunbind(intent arg0) { // auto-generated method return null; } public void onstop() { } public void onpause() { } @override public void ondestroy() { player.stop(); player.release(); } @override public void onlowmemory() { } }
starting with
intent svc = new intent(this, backgroundsoundservice.class); startservice(svc);
android manifest:
<service android:enabled="true" android:name=".backgroundsoundservice" />
this happened because service still bounded in activity. terminate service when multiple activity bound service, need unbind service of them in documentation says:
the service lifecycle—from when it's created when it's destroyed—can follow either of these 2 paths:
a started service
the service created when component calls startservice(). service runs indefinitely , must stop calling stopself(). component can stop service calling stopservice(). when service stopped, system destroys it.
a bound service
the service created when component (a client) calls bindservice(). client communicates service through ibinder interface. client can close connection calling unbindservice(). multiple clients can bind same service , when of them unbind, system destroys service. service not need stop itself.
these 2 paths not entirely separate. can bind service started startservice(). example, can start background music service calling startservice() intent identifies music play. later, possibly when user wants exercise control on player or information current song, activity can bind service calling bindservice(). in cases such this, stopservice() or stopself() doesn't stop service until of clients unbind.
then call context.stopservice()
stop it:
context.stopservice(new intent(context, backgroundsoundservice.class));
Comments
Post a Comment