android - how to stop music if application in background -


i'm trying stop music when user leave app or click (home button) , application plays music if in background, how can stop music if user click home button ? if user returns, music played again ? code :

protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);     mediaplayer = mediaplayer.create(getapplicationcontext(), r.raw.vaporv2);     if(!mediaplayer.isplaying()){         mediaplayer.start();     }     mediaplayer.setoncompletionlistener(new mediaplayer.oncompletionlistener() {         public void oncompletion(mediaplayer mp) {             mediaplayer.start();         }     }); //toggle off , on :     musicbutton = (togglebutton) findviewbyid(r.id.togglebutton);     musicbutton.setoncheckedchangelistener(new oncheckedchangelistener() {         @override         public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) {             if (musicbutton.ischecked() && mediaplayer.isplaying()) {                 mediaplayer.pause();              } else {                 mediaplayer.start();             }         }     }); 

in activity:

check 2 states:

on pause state: when press home button

 @override     protected void onpause() {         super.onpause();         if(mediaplayer!=null && mediaplayer.isplaying()){             mediaplayer.pause();         }     } 

on resume state: when come screen

@override     protected void onresume() {         super.onresume();         if(mediaplayer!=null && !mediaplayer.isplaying()){             mediaplayer.start();         }     } 

Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -