The use of Android-service

Source: Internet
Author: User

Service is run in the background, not visible, no interface page, priority is higher than activity, can be used to play music, record geographic information location change, listen to some kind of action, type has two kinds, one is local service, there are start and bind two kinds of starting mode, the other is remote service.

Target effect:

Program run shows all the button controls, divided into two categories, the top is start and stop, the bottom is the bind start and stop, click the output corresponding to the life cycle of the method content.


1.activity_main.xml the page to place all button controls.

Activity_main.xml page:

<relativelayout 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 "Tools:context =". Mainactivity "> <textview android:id=" @+id/tvstart "android:layout_width=" Wrap_content "Android        oid:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_alignparenttop= "true" android:text= "Start:"/> <button android:id= "@+id/btstart" android:layout_width= "Wrap_conten T "android:layout_height=" Wrap_content "android:layout_alignparentleft=" true "Android:layout_alignpar Entright= "true" android:layout_below= "@+id/tvstart" android:text= "StartService"/> <button A Ndroid:id= "@+id/btstop" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android Oid:layout_alignparentleft= "true" aNdroid:layout_alignparentright= "true" android:layout_below= "@+id/btstart" android:text= "StopService"/> <textview android:id= "@+id/tvbind" android:layout_width= "wrap_content" android:layout_height= "WR Ap_content "android:layout_alignparentleft=" true "android:layout_below=" @+id/btstop "android:text=" Bi Nd: "/> <button android:id=" @+id/btbind "android:layout_width=" Wrap_content "Android:layout_ height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_alignparentright= "true" an droid:layout_below= "@+id/tvbind" android:text= "Bindservice"/> <linearlayout android:id= "@+id/chang Eone "android:layout_width=" match_parent "android:layout_height=" Wrap_content "android:layout_below="            @+id/btbind "android:orientation=" horizontal "> <button android:id=" @+id/btprevious " Android:layout_widtH= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentright= "true"            android:layout_weight= "1" android:text= "previous"/> <button android:id= "@+id/btnext" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_ali    Gnparentright= "true" android:layout_weight= "1" android:text= "Next"/> </LinearLayout> <linearlayout android:id= "@+id/changetwo" android:layout_width= "Match_parent" Android:layout_heigh t= "Wrap_content" android:layout_below= "@+id/changeone" android:orientation= "Horizontal" > <Butt On android:id= "@+id/btplay" android:layout_width= "wrap_content" android:layout_height= "WR Ap_content "android:layout_alignparentright=" true "android:layout_weight=" 1 "android:text = "Play"/> <bUtton android:id= "@+id/btpause" android:layout_width= "Wrap_content" android:layout_height = "Wrap_content" android:layout_alignparentright= "true" android:layout_weight= "1" android: text= "Pause"/> </LinearLayout> <button android:id= "@+id/btunbind" android:layout_width= "wrap _content "android:layout_height=" Wrap_content "android:layout_alignparentleft=" true "android:layout_a Lignparentright= "true" android:layout_below= "@+id/changetwo" android:text= "Unbindservice"/></Relative Layout>


2. New Mystartservice.java page inherits service, overriding method called when Start mode starts. Mystartservice.java page:
Package Com.example.service;import Android.app.service;import Android.content.intent;import android.os.IBinder; Import Android.util.log;public class Mystartservice extends service{@Overridepublic ibinder onbind (Intent arg0) {log.i ( "Mainactivity", "Startservice--onbind ()"); return null;} @Overridepublic void OnCreate () {log.i ("mainactivity", "Startservice--onceate ()"); Super.oncreate ();} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {log.i ("mainactivity", " Startservice--onstartcommand () "); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic void OnDestroy () {Super.ondestroy (); LOG.I ("Mainactivity", "Startservice--ondestroy ()");}}


3. New Mybindservice.java page inherits service, overriding method, called when Bind mode is started. Mybindservice.java page:
Package Com.example.service;import Android.app.service;import Android.content.intent;import Android.content.serviceconnection;import Android.os.binder;import Android.os.ibinder;import Android.util.Log; public class Mybindservice extends service{/* define class inherit Binder return service object */public class Mybinder extends Binder{public Mybindservice GetService () {return mybindservice.this;}} @Overridepublic ibinder onbind (Intent arg0) {log.i ("mainactivity", "Bindservice--onbind ()"); return new Mybinder ();// Instance service object and returns} @Overridepublic void OnCreate () {super.oncreate (); LOG.I ("Mainactivity", "Bindservice--onceate ()");} @Overridepublic void Unbindservice (Serviceconnection conn) {Super.unbindservice (conn); LOG.I ("Mainactivity", "Bindservice--unbindservice ()");} @Overridepublic void OnDestroy () {Super.ondestroy (); LOG.I ("Mainactivity", "Bindservice--ondestroy ()");} public void Play () {log.i ("mainactivity", "Play");} public void Pause () {log.i ("mainactivity", "pause");} public void Previous () {log.i ("mainactivity", "previous");} public void Next () {LOG.I("Mainactivity", "Next Song");}} 


4. For the new two service, you need to register on the Androidmanifest.xml page. Androidmanifest.xml page:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.example.service "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion="/> <application android:allowbackup= "t Rue "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/appt Heme "> <activity android:name=" com.example.service.MainActivity "android:label=" @strin G/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/&gt                ; <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity&                Gt <!--registration Service--<service android:name= "Com.example.service.myStartService" ></service> & LtService android:name= "Com.example.service.myBindService" ></service> </application></manifest >


The 5.mainactivity.java page is bound to the Click event. Mainactivity.java page:
Package Com.example.service;import Com.example.service.mybindservice.mybinder;import Android.os.Bundle;import Android.os.ibinder;import Android.app.activity;import Android.app.service;import Android.content.ComponentName; Import Android.content.intent;import Android.content.serviceconnection;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class MainActivity Extends Activity implements Onclicklistener {private Button Btstart, Btstop, Btbind, btprevious, Btnext, Btplay,btpause, b Tunbind;private Intent intentstart,intentbind;private mybindservice service;/* Get service object */private ServiceConnection Conn =new serviceconnection () {/* This method is called when the connection to the startup source and service is lost unexpectedly, such as when the service crashes or is forcibly killed */@Overridepublic void onservicedisconnected (componentname arg0) {}/* This method will be called automatically when the boot source is successfully connected to the service */@Overridepublic void onserviceconnected (componentname name, IBinder binder) {service= ((mybinder) binder). GetService ();//Get Service object}};@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); GetId (); Bindclick ();} private void GetId () {Btstart = (button) Findviewbyid (r.id.btstart); btstop = (Button) Findviewbyid (r.id.btstop); btbind = (button) Findviewbyid (r.id.btbind), btprevious = (button) Findviewbyid (r.id.btprevious); btnext = (Button) Findviewbyid (r.id.btnext); btplay = (Button) Findviewbyid (r.id.btplay); btpause = (Button) Findviewbyid (r.id.btpause); btunbind = ( Button) Findviewbyid (r.id.btunbind);} private void Bindclick () {Btstart.setonclicklistener (this), Btstop.setonclicklistener (this); Btbind.setonclicklistener (This), Btprevious.setonclicklistener (This), Btnext.setonclicklistener (this); Btplay.setonclicklistener (This), Btpause.setonclicklistener (This), Btunbind.setonclicklistener (this);} @Overridepublic void OnClick (view view) {switch (View.getid ()) {Case R.id.btstart:intentstart=new Intent ( Mainactivity.this,mystartservice.class); StartService (Intentstart); Break;casE R.id.btstop:stopservice (Intentstart); break;case r.id.btplay:service.play (); Break;case R.id.btPause: Service.pause (); break;case r.id.btprevious:service.previous (); break;case r.id.btnext:service.next (); break;case r.id.btbind://binds intentbind=new Intent (mainactivity.this,mybindservice.class);//The first argument is an instance of the Intent object, The second parameter is the resulting service object Bindservice (Intentbind, conn,service.bind_auto_create); Break;case r.id.btunbind://is unbound and can only be clicked once, And if you want to end the startup source, you must unbind Unbindservice (conn);


6. The operation will show the target effect.






The use of Android-service

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.