Android Growth Diary-android four components of service component learning

Source: Internet
Author: User

1. What is a service?

Service is the most similar component in Android's four components, they all represent the executable program, the difference between service and activity is that the service is running in the background, it has no user interface, so it never comes to the foreground. Once the service is started, it is the same as the activity. It completely has its own life cycle.

A Service is an application component so can perform long-running operations in the background and does not p Rovide a user interface. Another application component can start a service and it would continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provide R, all from the background. (from the official explanation: http://developer.android.com/guide/components/services.html )

2. The small series after access to information, the following is the relevant information of the service:

Definition: Running in the background, not visible, no interface
Priority is higher than activity
Use:
Play music, record geographic information location changes, listen to some kind of action .....
Attention:
Run on the main thread, can't use it to make time-consuming requests or actions
You can open a thread in the service and take the time-consuming action in the process
Type:
1. On-Premises Services (Local service)
Inside the application
StartService StopService stopself Stopselfresult
Bindservice Unbindservice
2. Remote Service
Between Android system internal programs
Defining the IBinder interface
Start Mode Features
1. The service does not have any connection with the startup source
2. Unable to get service object
Bind Mode Features
1. Through the IBinder interface instance, return a Serviceconnection object to the startup source
2. The service object can be obtained by means of the Serviceconnection object

3. The following mini-series will tell the service through a demo:

& Steps to implement the service: 1. Create a class to inherit the service, complete the necessary methods, 2. Register in the Androidminifast file 3. Call

Before that, the gadget will tell about a startup through StartService Servie

 PackageCom.demo.internet.musicapp;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.IBinder;ImportAndroid.util.Log;/*** Created by Monster on 2015/7/2. * Starting the service by Start mode, features of this service: * 1. The service has no contact with the startup source * 2. Unable to get service object*/ Public classMusicserviceextendsService {@Override Public voidonCreate () {LOG.I ("Info", "service--oncreate ()"); Super. OnCreate (); } @Override Publicibinder onbind (Intent Intent) {log.i ("Info", "Service--onbind ()"); return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {LOG.I ("Info", "Service--onstartcommand ()"); return Super. Onstartcommand (Intent, flags, Startid); } @Override Public voidOnDestroy () {LOG.I ("Info", "Service--ondestroy ()"); Super. OnDestroy (); }}

Call:

Intent1 =new Intent (mainactivity.  this, Mystartservice. class ); StartService (intent1);

--------------------------------------------------------------------------------------------------------------- ----------------------------

The following small series by using the Bindservice way to achieve the playback of music demo

①. Layout does not tell

②. Create a Bindmusicservice.java to inherit the service and register it

 PackageCom.demo.internet.musicapp;ImportAndroid.app.Service;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.media.MediaPlayer;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;ImportAndroid.util.Log;/*** Created by Monster on 2015/7/2. * Mode Features: * 1. Through the IBinder interface instance, return a Serviceconnection object to the startup source * 2. By the relevant party of the Serviceconnection object Method can get service object*/ Public classBindmusicserviceextendsService {PrivateMediaPlayer MPlayer;//declares a MediaPlayer object@Override Publicibinder onbind (Intent Intent) {log.i ("Info", "Bindservice--onbind ()"); return NewMybinder (); } @Override Public voidUnbindservice (Serviceconnection conn) {LOG.I ("Info", "Bindservice--unbindservice ()"); Super. Unbindservice (conn); } @Override Public voidonCreate () {LOG.I ("Info", "bindservice--oncreate ()"); Super. OnCreate (); MPlayer=mediaplayer.create (Getapplicationcontext (), r.raw.meizu_music);//instantiating an object//settings can be played repeatedlyMplayer.setlooping (true); } @Override Public voidOnDestroy () {LOG.I ("Info", "Bindservice--ondestroy ()"); Super. OnDestroy ();    Mplayer.stop (); }    //The Binderservice service must be obtained by inheriting binder     Public classMybinderextendsbinder{ PublicBindmusicservice GetService () {returnBindmusicservice. This; }    }     Public voidPlay () {LOG.I ("Info", "Play");    Mplayer.start (); }     Public voidPause () {LOG.I ("Info", "pause");    Mplayer.pause (); }}

③. Create the Serviceconnection interface in mainactivity and implement the non-implemented method, and then create the Bindmusicservice declaration, called when the Bindservice method is called

 PackageCom.demo.internet.musicapp;Importandroid.app.Activity;ImportAndroid.content.ComponentName;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.Toast; Public classMainactivityextendsActivityImplementsview.onclicklistener{PrivateButton Btn_start,btn_stop,bind_btn_start,bind_btn_stop,bind_btn_play,bind_btn_pause;    Intent Intent1;    Intent Intent2;    Bindmusicservice Service; Serviceconnection Con=Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder binder) {//automatically callback when the service is connected to the startup sourceService=( (Bindmusicservice.mybinder) binder). GetService (); } @Override Public voidonservicedisconnected (componentname name) {//automatically callbacks when the service is disconnected from the startup source        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); }    Private voidInitview () {Btn_start=(Button) Findviewbyid (R.id.btn_start); Btn_stop=(Button) Findviewbyid (r.id.btn_stop); Bind_btn_start=(Button) Findviewbyid (R.id.bind_btn_start); Bind_btn_stop=(Button) Findviewbyid (r.id.bind_btn_stop); Bind_btn_play=(Button) Findviewbyid (R.id.bind_btn_play); Bind_btn_pause=(Button) Findviewbyid (r.id.bind_btn_pause); //Binding Listener EventsBtn_start.setonclicklistener ( This); Btn_stop.setonclicklistener ( This); Bind_btn_start.setonclicklistener ( This); Bind_btn_stop.setonclicklistener ( This); Bind_btn_play.setonclicklistener ( This); Bind_btn_pause.setonclicklistener ( This); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btn_start://intent1=new Intent (mainactivity.this,musicservice.class); //StartService (intent1);                 Break;  CaseR.id.btn_stop://StopService (intent1);                 Break;  CaseR.id.bind_btn_start:intent2=NewIntent (mainactivity. This, Bindmusicservice.class); Bindservice (intent2,con,bind_auto_create);//Binding Service                 Break;  CaseR.id.bind_btn_play:service.                Play ();  Break;  CaseR.id.bind_btn_pause:service.                Pause ();  Break;  CaseR.id.bind_btn_stop:unbindservice (con);//Unbind Service                 Break; }    }}

--------------------------------------------------------------------------------------------------------------- ----------------------------

4. Demo:

5. Source code sharing:

Https://git.coding.net/monsterLin/MusicAppService.git

Android Growth Diary-android four components of service component learning

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.