Teach you to easily make Android music player _android

Source: Internet
Author: User
Tags stub

Enjoy our refreshing interface.

If it's just an activity to make something like that, it's too small for pediatrics, and of course we're using service.
First we start with the service code:
1. If we want to access the properties and methods of the service, then the activity must be implemented in a bindservice way, and the Onbind method in the service must be implemented, The IBinder object returned by Onbind is used in the serviceconnection of the activity.
2, the activity gets to the IBinder object, can further obtain the service object and the Player object, for the access.
3, Environment.getexternalstoragedirectory () is to obtain the content of SD, whether it is the mobile phone appeared on the built-in SD card, or the user later added their own SD card; Getexternalfilesdir () Get the real phone inside of the storage space,/data/data/your_package/, as the application unloads the stored files will be deleted.
4. Service interacts with activity through sending broadcast

public class Musicservice extends service{private list<file> musiclist;
 Private MediaPlayer player;
 private int curpage;
 public static final String mfilter = "Broadcast.intent.action.text";
 public static final String name = "Name";
 public static final String totaltime = "TotalTime";

 public static final String curtime = "Curtime";
 @Override public IBinder onbind (Intent Intent) {//1//TODO auto-generated method stub return new Mbinder ();
  public class Mbinder extends BINDER{//2 public musicservice GetService () {return musicservice.this;
  Public MediaPlayer Getplayer () {return player;
  @Override public void OnCreate () {//TODO auto-generated Method Stub super.oncreate ();
  Musiclist = new arraylist<file> ();
  File RootDir = Environment.getexternalstoragedirectory ();//3 log.d ("Rootname", Rootdir.getname ());
  LOG.D ("Rootname", Rootdir.getabsolutepath ());
  Fillmusiclist (RootDir); LOG.D ("Musiclist", string.valueof (musiclist.size)));
  Player = new MediaPlayer ();
  if (musiclist.size ()!= 0) {startplay (); Player.setoncompletionlistener (New Oncompletionlistener () {@Override public void oncompletion (Mediaplaye
    R MP) {//TODO auto-generated Method Stub player.reset (); Curpage = Curpage==musiclist.size ()-1? 
    (curpage+1)%musiclist.size (): curpage+1;
   Startplay ();
 }
  });
  /* Iterate to get the music file */private void Fillmusiclist (file dir) {file[] SourceFiles = Dir.listfiles ();
  LOG.D ("Length", string.valueof (Sourcefiles.length)); for (File file:sourcefiles) {if (File.isdirectory ()) {LOG.D (folder name, String.valueof (File.getname ()));//if (!f Ile.getname (). Equals ("Lost+found")) {fillmusiclist (file);//}} else {String name = File.getna
     Me ();
     LOG.D ("ChildName", File.getname ()); if (Name.endswith (". mp3") | |
     Name.endswith (". ACC")) {//Supported format musiclist.add (file); '}}} private void Startplay () {msendbroadcast (name,musiclist.get) (curpage). GetName ());//4 try {player.setdatasource (Musiclist.get (curpage). GetAbsolutePath ());
   Player.prepare ();
   Player.start ();
   Player.getduration ();
   Msendbroadcast (Totaltime,player.getduration ());
   Timer timer = new timer (); Timer.schedule (New TimerTask () {@Override public void run () {//TODO auto-generated method stub m
    Sendbroadcast (Curtime,player.getcurrentposition ());
   
  }},0,1000);
  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 (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } public void PlayNext () {curpage = Curpage==musiclist.size ()-1? 
  (curpage+1)%musiclist.size (): curpage+1;
  LOG.D ("Curpage", String.valueof (Curpage)); PlAyer.reset ();
 Startplay (); 
  public void Playprevious () {curpage = curpage==0? 0:curpage-1;
  LOG.D ("Curpage", String.valueof (Curpage));
  Player.reset ();
 Startplay ();
 public void Parse () {player.pause ();
 public void Restart () {Player.start ();
  private void Msendbroadcast (string key, String value) {Intent Intent = new Intent (mfilter);
 Intent.putextra (key,value);/Send broadcast sendbroadcast (intent);
  private void Msendbroadcast (String key, int value) {Intent Intent = new Intent (mfilter);
 Intent.putextra (key,value);/Send broadcast sendbroadcast (intent);

 }
}

The next activity code:
1, getting service objects
2 through the IBinder object, and then accessing the service's methods after getting to the service object.
3, Refresh page by receiver

public class Mainactivity extends activity implements onclicklistener{SeekBar SeekBar;
 TextView Curtime,totaltime;
 
 TextView title;
 Private Serviceconnection SC;
 Private Musicservice MS;
 Private Boolean isstop; 
 Private double totaltimeint;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Intentfilter filter = new Intentfilter (musicservice.mfilter);
  Registerreceiver (New Musicreceiver (), filter); sc = new Serviceconnection () {@Override public void onservicedisconnected (componentname name) {//TODO Aut
   o-generated method Stub ms = NULL; @Override public void onserviceconnected (componentname name, IBinder service) {//TODO auto-generated met
  Hod Stub ms = ((mbinder) service). GetService ();//1}};
  Button previous = (button) Findviewbyid (r.id.previous);
  button next = (Button) Findviewbyid (R.id.next); Button stop = (button) FIndviewbyid (R.id.stop);
  Button StopService = (button) Findviewbyid (R.id.stopservice);
  SeekBar = (SeekBar) Findviewbyid (R.id.mseekbar);
  Curtime = (TextView) Findviewbyid (r.id.curtime);
  TotalTime = (TextView) Findviewbyid (r.id.totaltime);
  
  title = (TextView) Findviewbyid (r.id.title);
  Previous.setonclicklistener (this);
  Next.setonclicklistener (this);
  Stop.setonclicklistener (this);
 Stopservice.setonclicklistener (this); @Override public void OnClick (View v) {//TODO auto-generated Method Stub switch (V.getid ()) {case R.id.previ
  Ous:ms.playPrevious ();//2 break;
   Case R.id.next:ms.playnext ();
  Break
   Case R.id.stop:if (isstop) {Ms.restart ();
   else {ms.parse ();
   } isstop =!isstop;
  Break
   Case R.id.stopservice:intent Intent = new Intent ("Com.intent.musicplayer.MusicService");
   Unbindservice (SC);

   StopService (Intent);
  Break
  Default:break; } @Override protected void OnStart () {//TODO Auto-generated method Stub Super.onstart ();
  Intent Intent = new Intent ("Com.intent.musicplayer.MusicService");
 Bindservice (intent,sc,context.bind_auto_create); You can, of course, start the service in a startservice way, so that when you end the activity, it does not end service}
  Private String transfermillitotime (int millis) {dateformat format = new SimpleDateFormat ("Mm:ss");
  String result = Format.format (new Date (Millis));
 return result; Private class Musicreceiver extends BROADCASTRECEIVER{//3 @Override public void onreceive (context context, Intent Intent) {//TODO auto-generated Method stub if (Intent.getintextra (musicservice.curtime,0)!=0) {double curtime
    Int = Intent.getintextra (musicservice.curtime,0);
    Curtime.settext (transfermillitotime (int) curtimeint));
    Double result = curtimeint/totaltimeint*100;
    
   Seekbar.setprogress ((int) Math.floor (result)); else if (Intent.getintextra (musicservice.totaltime,0)!=0) {totaltimeint = Intent.getintextra (MusicService.TOTALTI
    me,0); Totaltime.sEttext (transfermillitotime (int) (totaltimeint)); else if (! Textutils.isempty (Intent.getstringextra (musicservice.name))) {Title.settext (Intent.getstringextra (
   Musicservice.name));

 }
  }
  
 }
}

4, the last attached XML layout file, the code is uploaded completely:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:o" rientation= "vertical" tools:context= "${relativepackage}.${activityclass}" "> <textview android:id=" @+id/title "Android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:layout_gravity=" Center_ Horizontal "android:textsize=" 25sp "android:textcolor=" #444444 "/> <seekbar android:id=" @+id/mseekbar "a
  Ndroid:layout_gravity= "Center_horizontal" android:layout_width= "400DP" android:layout_height= "Wrap_content" android:max= "/> <relativelayout android:layout_width=" match_parent "android:layout_height=" wrap_content "> <textview android:id=" @+id/curtime "android:layout_height=" wrap_content "android:layout_width=" Wrap_co Ntent "android:layout_alignparentleft=" true "/> <textview AndrOid:id= "@+id/totaltime" android:layout_height= "wrap_content" android:layout_width= "Wrap_content" Android:layout_ Alignparentright= "true"/> </RelativeLayout> <relativelayout android:layout_width= "Match_parent" Andr
  oid:layout_height= "Wrap_content" > <button android:id= "@+id/previous" android:layout_height= "Wrap_content" 
   Android:layout_width= "Wrap_content" android:text= "Last Song" android:layout_alignparentleft= "true"/> <Button Android:id= "@+id/stop" android:layout_height= "wrap_content" android:layout_width= "wrap_content" android:text= "stop Music "android:layout_torightof=" @id/previous "/> <button android:id=" @+id/next "android:layout_height=" WR
   Ap_content "android:layout_width=" Wrap_content "android:text=" Next "android:layout_alignparentright=" true "/> <button android:id= "@+id/stopservice" android:layout_height= wrap_content "android:layout_width=" Wrap_conten
T "android:text= Stop music Service"   android:layout_toleftof= "@id/next"/> </RelativeLayout> </LinearLayout>
 

The above is the production of Android music player all the code, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.