Android Activity to Service class -


i have activity below plays shoutcasturl streaming using helper classess

code:

import java.net.malformedurlexception;  import com.androidworkz.androidshoutcastlib.androidshoutcastlib; import com.androidworkz.androidshoutcastlib.invalidstreamurlexception; import com.androidworkz.androidshoutcastlib.metadata; import com.androidworkz.androidshoutcastlib.metadatalistener;  import android.media.audiomanager; import android.media.mediaplayer; import android.media.mediaplayer.onbufferingupdatelistener; import android.media.mediaplayer.oncompletionlistener; import android.media.mediaplayer.onerrorlistener; import android.media.mediaplayer.onpreparedlistener; import android.os.bundle; import android.os.handler; import android.os.powermanager; import android.app.activity; import android.util.log; import android.view.menu; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.textview;  public class player extends activity implements oncompletionlistener, onpreparedlistener, onerrorlistener, onbufferingupdatelistener, musicfocusable {      private boolean playstate = false;       private string station = "http://38.101.195.5:9156";     public static final float duck_volume = 0.1f;     private string artistname = null;     private string trackname = null;      private textview artist;     private textview track;     private textview status;     private button play;      enum audiofocus {         nofocusnoduck, // don't have audio focus, , can't duck         nofocuscanduck, // don't have focus, can play @ low volume                         // ("ducking")         focused // have full audio focus     }      private audiofocus maudiofocus = audiofocus.nofocusnoduck;      private mediaplayer mplayer = null;     private androidshoutcastlib shoutcast;     private audiomanager maudiomanager;     audiofocushelper maudiofocushelper = null;      handler handler = new handler();      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_player);          maudiomanager = (audiomanager) getsystemservice(audio_service);          // create audio focus helper, if audio focus feature         // available (sdk 8 or above)         if (android.os.build.version.sdk_int >= 8) {             maudiofocushelper = new audiofocushelper(getapplicationcontext(),                     this);         }         else {             maudiofocus = audiofocus.focused; // no focus feature, "have" audio focus         }          status = (textview) findviewbyid(r.id.status);          artist = (textview) findviewbyid(r.id.artist);         artist.setselected(true);          track = (textview) findviewbyid(r.id.track);         track.setselected(true);          play = (button) findviewbyid(r.id.play);          play.setonclicklistener(new onclicklistener() {              @override             public void onclick(view btn) {                 if (!playstate) {                     play.settext("pause");                     handler.postdelayed(handleplayrequest, 300);                 }                 else {                     play.settext("play");                     status.settext("press play");                     handler.postdelayed(handleplayrequest, 300);                 }             }          });          shoutcast = new androidshoutcastlib();          try {             shoutcast.setshoutcasturl(station);         } catch (invalidstreamurlexception e) {             // todo auto-generated catch block             e.printstacktrace();         }          shoutcast.setonmetadatachangedlistener(new metadatalistener(){              @override             public void onmetadatachanged(metadata item) {                 artistname = item.artist;                 trackname = item.track;                              updatemeta();             }         });          setvolumecontrolstream(audiomanager.stream_music);           }      public void ondestroy() {         super.ondestroy();          shoutcast = null;         handler.removecallbacks(handleplayrequest);     }      public void updatemeta() {         handler.post(new runnable() {             @override             public void run() {                 // gets executed on ui thread can safely modify views                 artist.settext(artistname);                 track.settext(trackname);             }         });     }      private final runnable handleplayrequest = new runnable() {         public void run() {             if (playstate) {                 log.d("player", "stop called");                 giveupaudiofocus();                 mplayer.stop();                 mplayer.reset();                 mplayer.release();                 shoutcast.stopstream();                 mplayer = null;                 playstate = false;             }             else {                 log.d("player", "play called");                 createmediaplayer();                 getaudiofocus();                  try {                     mplayer.setdatasource(shoutcast.startstream());                 } catch (illegalargumentexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (securityexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (illegalstateexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (malformedurlexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (ioexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (invalidstreamurlexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 }                 mplayer.prepareasync();             }         }     };      private void createmediaplayer() {         mplayer = new mediaplayer();          // make sure media player acquire wake-lock while         // playing. if don't         // that, cpu might go sleep while song playing,         // causing playback stop.         //         // remember use this, have declare         // android.permission.wake_lock         // permission in androidmanifest.xml.         mplayer.setwakemode(getapplicationcontext(),                 powermanager.partial_wake_lock);          // want media player notify when it's ready preparing,         // , when it's done         // playing:         mplayer.setonpreparedlistener(this);         mplayer.setoncompletionlistener(this);         mplayer.setonerrorlistener(this);     }      private void startplayer() {         mplayer.setvolume(1.0f, 1.0f);         if (!mplayer.isplaying()) {             log.d("player", "starting playback");             mplayer.start();             playstate = true;             status.settext("streaming");         }                    }      private void getaudiofocus() {         if (maudiofocus != audiofocus.focused && maudiofocushelper != null                 && maudiofocushelper.requestfocus())             maudiofocus = audiofocus.focused;     }      private void giveupaudiofocus() {         if (maudiofocus == audiofocus.focused && maudiofocushelper != null                 && maudiofocushelper.abandonfocus())             maudiofocus = audiofocus.nofocusnoduck;     }      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.activity_player, menu);         return true;     }      @override     public void onbufferingupdate(mediaplayer arg0, int arg1) {         // todo auto-generated method stub      }      @override     public boolean onerror(mediaplayer mp, int what, int extra) {         playstate = false;         handler.post(handleplayrequest);         return false;     }      @override     public void onprepared(mediaplayer arg0) {         startplayer();           }      @override     public void oncompletion(mediaplayer arg0) {         // todo auto-generated method stub      }      @override     public void ongainedaudiofocus() {         // todo auto-generated method stub      }      @override     public void onlostaudiofocus(boolean canduck) {         // todo auto-generated method stub      }  } 

the above code working perfect when played stream in foreground,

but requirement play stream in background also(my code should play stream,if user interacting other applications also)

for ,i have created service class above activity

here code:

activity:

import android.os.bundle; import android.app.activity; import android.content.intent; import android.util.log; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.textview;  public class player extends activity implements onclicklistener {      private boolean playstate = false;     public static final float duck_volume = 0.1f;     private string artistname = null;     private string trackname = null;      private textview artist;     private textview track;     private textview status;     private button play;      intent playbackserviceintent;      protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_player);          // create audio focus helper, if audio focus feature         // available (sdk 8 or above)          status = (textview) findviewbyid(r.id.status);          artist = (textview) findviewbyid(r.id.artist);         artist.setselected(true);          track = (textview) findviewbyid(r.id.track);         track.setselected(true);          play = (button) findviewbyid(r.id.play);          play.setonclicklistener(this);          playbackserviceintent = new intent(this, backgroundservice.class);      }      @override     public void onclick(view v) {         if (v == play) {             startservice(playbackserviceintent);             log.d("hi>>>>>", "gjgj");             finish();         }     }  } 

service class:

import com.androidworkz.androidshoutcastlib.androidshoutcastlib; import com.androidworkz.androidshoutcastlib.invalidstreamurlexception;  import android.app.service; import android.content.intent; import android.media.audiomanager; import android.media.mediaplayer; import android.media.mediaplayer.onbufferingupdatelistener; import android.media.mediaplayer.oncompletionlistener; import android.media.mediaplayer.onerrorlistener; import android.media.mediaplayer.onpreparedlistener; import android.os.asynctask; import android.os.handler; import android.os.ibinder; import android.os.powermanager; import android.util.log;  public class backgroundservice extends service implements oncompletionlistener,         onpreparedlistener, onerrorlistener, onbufferingupdatelistener,         musicfocusable {     private boolean playstate = false;     private string station = "http://38.101.195.5:9156";     public static final float duck_volume = 0.1f;     runnable handleplayrequest;      enum audiofocus {         nofocusnoduck, // don't have audio focus, , can't duck         nofocuscanduck, // don't have focus, can play @ low volume                         // ("ducking")         focused // have full audio focus     }      private audiofocus maudiofocus = audiofocus.nofocusnoduck;      private mediaplayer mplayer = null;     private androidshoutcastlib shoutcast;     private audiomanager maudiomanager;     audiofocushelper maudiofocushelper = null;      handler handler = new handler();      @override     public ibinder onbind(intent arg0) {         // todo auto-generated method stub         return null;     }      @override     public int onstartcommand(intent intent, int flags, int startid) {         log.d("onstartcommand>>>", "onstartcommand");          maudiomanager = (audiomanager) getsystemservice(audio_service);          // create audio focus helper, if audio focus feature         // available (sdk 8 or above)         if (android.os.build.version.sdk_int >= 8) {             maudiofocushelper = new audiofocushelper(getapplicationcontext(),                     this);         } else {             maudiofocus = audiofocus.focused; // no focus feature,                                                 // "have" audio focus         }         shoutcast = new androidshoutcastlib();          try {             log.d("station>>>", station);              shoutcast.setshoutcasturl(station);          } catch (invalidstreamurlexception e) {             // todo auto-generated catch block             e.printstacktrace();         }          new backgroundsound().execute();          return start_sticky;     }      public void ondestroy() {         log.d("ondestroy>>>", "ondestroy");          if (mplayer.isplaying()) {             mplayer.stop();         }         mplayer.release();     }      @override     public void ongainedaudiofocus() {         // todo auto-generated method stub      }      @override     public void onlostaudiofocus(boolean canduck) {         // todo auto-generated method stub      }      @override     public void onbufferingupdate(mediaplayer arg0, int arg1) {         // todo auto-generated method stub      }      @override     public boolean onerror(mediaplayer arg0, int arg1, int arg2) {         // todo auto-generated method stub         return false;     }      @override     public void onprepared(mediaplayer arg0) {         // todo auto-generated method stub         mplayer.start();     }      private void giveupaudiofocus() {         if (maudiofocus == audiofocus.focused && maudiofocushelper != null                 && maudiofocushelper.abandonfocus())             maudiofocus = audiofocus.nofocusnoduck;     }      @override     public void oncompletion(mediaplayer arg0) {         // todo auto-generated method stub         stopself();     }      private void getaudiofocus() {         if (maudiofocus != audiofocus.focused && maudiofocushelper != null                 && maudiofocushelper.requestfocus())             maudiofocus = audiofocus.focused;     }      private void createmediaplayer() {         mplayer = new mediaplayer();          // make sure media player acquire wake-lock while         // playing. if don't         // that, cpu might go sleep while song playing,         // causing playback stop.         //         // remember use this, have declare         // android.permission.wake_lock         // permission in androidmanifest.xml.         mplayer.setwakemode(getapplicationcontext(),                 powermanager.partial_wake_lock);          // want media player notify when it's ready preparing,         // , when it's done         // playing:         mplayer.setonpreparedlistener(this);         mplayer.setoncompletionlistener(this);         mplayer.setonerrorlistener(this);     }      private class backgroundsound extends asynctask<void, void, void> {         @override         protected void doinbackground(void... params) {             log.d("doinbackground>>>", "doinbackground");              log.d("run>>>", "run");              if (playstate) {                 log.d("player", "stop called");                 giveupaudiofocus();                 mplayer.stop();                 mplayer.reset();                 mplayer.release();                 shoutcast.stopstream();                 mplayer = null;                 playstate = false;             } else {                 log.d("player", "play called");                 createmediaplayer();                 getaudiofocus();                  try {                     mplayer.setdatasource(shoutcast.startstream());                 } catch (illegalargumentexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (securityexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (illegalstateexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (malformedurlexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (ioexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 } catch (invalidstreamurlexception e) {                     // todo auto-generated catch block                     e.printstacktrace();                 }                 mplayer.prepareasync();             }              return null;         }     }  } 

when execute above service class,i'm able play stream,but layout disappering when control comes service class

one thing,i want know that,my conversion activity service correct or not?

could 1 suggest me correct code?

if want play background music app only, play in thread launched app/use asynctask class you.

the concept of services run in background; background, meaning when app ui not visible. true, can used have (if remember stop it) not right, , consumes resources shouldn't using.

if want peform tasks on background of activity, use asynctask.

by way, onstart deprecated. when use services, implement onstartcommand.

update:

i think code work you. add class (enclosed in activity class).

        public class backgroundsound extends asynctask<void, void, void> {           @override         protected void doinbackground(void... params) {         mediaplayer player = mediaplayer.create(youractivity.this, r.raw.test_cbr);          player.setlooping(true); // set looping          player.setvolume(100,100);          player.start();          return null;              }          } 

now, in order control music, save backgroundsound object instead of creating annonymously. declare field in activity:

        backgroundsound mbackgroundsound = new backgroundsound(); 

on activity's onresume method, start it:

         public void onresume() {            super.onresume();             mbackgroundsound.execute(null);            } 

and on activity's onpause method, stop it:

         public void onpause() {            super.onpause();             mbackgroundsound.cancel(true);                  } 

this work.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

javascript - Clean way to programmatically use CSS transitions from JS? -

android - send complex objects as post php java -