Android Four component Learning summary and individual component examples (2)

Source: Internet
Author: User

The previous blog explains activity, content provider, this article blog carefully summed up service, broadcast receiver;

3. Service

> What is a service?
>windows Service: No interface for long-term background running programs.
>android Service: Is a component of the application, the long-run background of the activity without the interface

# #绑定服务调用服务方法的流程
1. Create a service that has a method inside the service that needs to be called.
public class Lingdaoservice extends Service
2. Create an intermediary within the service Mybinder implements the IBinder interface, inherits the Binder class, and the middleman has a method this method can indirectly invoke the internal method of the service.
/**
* Intermediary, in the service of the interior
*/
public class Mybinder extends binder{
/**
* Methods inside the call service
* @param money
*/
public void Callmethodinservice (int. money) {
if (money>2000) {
Methodinservice ();
}else{
Toast.maketext (Lingdaoservice.this, "Too little, you Know", 1). Show ();
}
}
}
3. Onbind method for implementing the service. Returns the Intermediary object.
Public IBinder Onbind (Intent Intent) {
return new Mybinder ();
}
4. In the activity, through the Bindservice method to bind the service.
Bindservice (SERIVCE, Conn, bind_auto_create);
5. If the service is successfully bound, execute the onserviceconnected () method to get the man-in-the-middle object.
public void onserviceconnected (componentname name, IBinder service) {
Mybinder = (mybinder) service;
System.out.println ("In the activity obtains the service successfully binds the return intermediary IBinder");
}
6. Indirectly invoke the method inside the service through the intermediary object.
Mybinder.callmethodinservice (5000);

Here are some examples of local music to explain the service:

First create a project project file and layout as follows to add the music file below the Res directory under the raw file:

1. According to the previous idea, the first is the layout, in layout below the Activity.xml in the following configuration:

<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:orientation= "vertical" >    <textview        android:id= "@+id/tvinfo"        android:layout_width = "Match_parent"        android:layout_height= "wrap_content"         />    <listview        android:id= "@+id/lv"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"/></linearlayout>

2. Then the Java code is written:

(1) First write the Bean class, create a Muscicinfo class, if in the enterprise project or large project, need to serialize.

Package Com.xunfang.bean;public class Muscicinfo {private String name;private int id;public String getName () {return name; }public void SetName (String name) {this.name = name;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public Muscicinfo (String name, int id) {super (); this.name = Name;this.id = ID;}}

(2) Writing service code is the middleman Code Musicservice.java code is as follows:

package Com.xunfang.musicservices;import Java.util.list;import Com.xunfang.bean.muscicinfo;import Android.app.service;import Android.content.intent;import Android.media.mediaplayer;import Android.os.binder;import Android.os.ibinder;public class MusicService extends Service {private MediaPlayer mp; @Overridepublic IBinder Onbind (Intent Intent) {return new Mymusicservice ();} public class Mymusicservice extends Binder{public void Playmusic (list<muscicinfo> list,int postion) {Play (List, postion); System.out.println ("has been visited here");} public void Stopmusic () {Stop ();}} Play song public void Play (list<muscicinfo> List, int postion) {if (mp!=null) {//description is playing, then stop playing mp.stop (); Release resource Mp.release (); MP = NULL;} System.out.println ("Song ID is:" +list.get (postion). GetId ());//Instantiate mp= mediaplayer.create (this, List.get (postion). getId ());//Play Song Mp.start ();} Stop song public void Stop () {if (MP! = null) {mp.stop (); Mp.release (); MP = NULL;}}} 

  (3) then play music in Mainactvity.java

Package Com.xunfang.music;import Java.util.arraylist;import Java.util.list;import com.xunfang.bean.MuscicInfo; Import Com.xunfang.musicservices.musicservice;import Com.xunfang.musicservices.MusicService.MyMusicService; Import Android.support.v7.app.actionbaractivity;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.view;import Android.view.viewgroup;import Android.widget.AdapterView; Import Android.widget.adapterview.onitemclicklistener;import Android.widget.baseadapter;import Android.widget.listview;import Android.widget.textview;public class Mainactivity extends Actionbaractivity {private TextView tv;private ListView lv;private list<muscicinfo> List = new arraylist<muscicinfo> ();p rivate Myconn Conn;private mymusicservice MMS; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (SA        Vedinstancestate); SetcontenTView (R.layout.activity_main);        TV = (TextView) Findviewbyid (r.id.tvinfo);        LV = (ListView) Findviewbyid (r.id.lv);        List.add (New Muscicinfo ("Big", R.raw.big));        List.add (New Muscicinfo ("Ice Rain", r.raw.by));                List.add (New Muscicinfo ("Glorious Years", r.raw.ghsy));        Lv.setadapter (New Myadapter ());        Intent Intent = new Intent (this,musicservice.class);        conn = new myconn ();                Bindservice (Intent, Conn, bind_auto_create); Lv.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> parent, View view,int position, long id) {Tv.settext ("the song being played is:" +list.get (position). GetName ()); Mms.playmusic (list, position)        ;}});  } Private class MyConn implements serviceconnection{@Overridepublic void onserviceconnected (componentname name, IBinder Service) {MMS = (mymusicservice) service; SYSTEM.OUT.PRINTLN ("1234");}        @Overridepublic void onservicedisconnected (componentname name) {}} private class Myadapter extends baseadapter{@Overridepublic int GetCount () {return list.size ();} @Overridepublic Object getItem (int position) {return null;} @Overridepublic long Getitemid (int position) {return 0;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {TextView TV = new TextView (mainactivity.th    is); Tv.settext (List.get (position). GetName ()); return TV;}    } @Override protected void OnDestroy () {Super.ondestroy ();    Mms.stopmusic ();    Unbindservice (conn); }}

The Java code is already written in this section and the next step is to configure the service in the manifest file as follows

<service
Android:name= "Com.xunfang.musicservices.MusicService"
></service>

The final thing is to run on the simulator or the real machine:

The next final component broadcast receiver 's next blog post summarizes.

Android Four component Learning summary and individual component examples (2)

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.