Stop background audio on android app -
im working on simple audio application have major problem because audio wont stop when user press home button or move app background
i tried use onpause() not work me please can ?
import android.media.mediaplayer; import android.support.v7.app.actionbaractivity; import android.os.bundle; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.button; public class mainactivity extends actionbaractivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); final button button1 = (button) findviewbyid(r.id.btn1); final mediaplayer angry = mediaplayer.create(mainactivity.this, r.raw.angry); button1.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { if(angry.isplaying()) { angry.pause(); button1.settext("play"); } else { angry.start(); angry.setlooping(true); button1.settext("pause"); } } });
you should pausing mediaplayer instance in onpause()
method.
code, final mediaplayer angry
exist in oncreate()
method local object variable. fix problem, need move out angry
object oncreate()
method, can access onpause()
method. here's example:
import android.media.mediaplayer; public class mainactivity extends actionbaractivity { mediaplayer angry; //now here @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); angry = mediaplayer.create(mainactivity.this, r.raw.angry);
and should pause in onpause()
method this:
@override public void onpause () { if (angry != null) { angry.pause(); angry.stop(); } super.onpause(); }
Comments
Post a Comment