Service is a serviced component of the Android system for developing features that do not have a user interface and run in the background for a long time
Service Introduction
Below I will briefly summarize the service basics into the following 6 points:
-what function does 1.Service apply to?
Service使用于无须用户干预,且有规则地运行或长期运行的后台共功能。
-Features of 2.Service
Service没有用户界面,相比于其他应用程序更加有利于降低系统资源的消耗。Service比Activity具有更高优先级,在资源紧张时,Service不会被Android系统优先终止。即使Service被系统终止,在系统资源恢复后Service也将自动回复运行状态,因此可以认为Service是在系统中可以稳定长期运行的组件。
-The usefulness of 3.Service
1.实现后台服务功能2.可用于进程间通信
-4.Service life cycle
完整的生命周期从onCreate()开始到onDestroy()结束,在onCreate()中完成Service的初始化工作,在onDestroy()中释放所有占用的资源。可以粗略的认为活动生命周期以onDestroy()标志结束。
-5. Using the service through the startup mode
Realize
通过Context.startService()启动Service,通过Context.stopService()停止Seivice。Context指其他组件,因此Service一定是由其它组件启动的,但停止过程可以通过其他组件或自身完成。
Characteristics
启动Service的组件无法获取Service的对象实例,因此也无法调用Service中的任何函数,也不能获取Service中的任何状态和数据信息。所以以启动方式的Service需要具备自管理的能力。
-6. Using the service through bindings
Realize
在其他组件中调用Context.bindService()建立服务连接,调用Context.unbindService()停止服务连接。如果在绑定过程中Service未启动,Context.bindService()会自动启动Service。
Characteristics
其他组件可以获取Service的实例对象并调用Service中的函数,可以获取Service中的状态和数据信息。同一个Service可以和被多个组件绑定服务连接,即同一个Service可以同时为多个组件服务。
Local Service
concept: Both the caller and the service of the local service are in the same program and are calls that do not require a cross-process to implement the service.
The following is a simple demo designed to a local service, including how to start and how to bind it. Main interface
Project structure
Randomservice.java (startup mode) complete code:
PackageCom.example.servicedemo;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.IBinder;Importandroid.support.annotation.Nullable;ImportAndroid.widget.Toast;/** * Created by Yinghao on 2016/5/6. * * Public class randomservice extends Service { / * Onstartcommand replaces OnStart but in Super.onstartcommand (intent, flags, Startid); method calls the OnStart () method (for compatibility) */< /c5> PrivateThread Workthread;@Override Public void onCreate() {Super. OnCreate (); Toast.maketext ( This,"Call OnCreate ()", Toast.length_short). Show (); Workthread =NewThread (NULL, BackgroundWork,"Workthread"); }@Override Public void OnStart(Intent Intent,intStartid) {Super. OnStart (Intent, Startid); Toast.maketext (Randomservice. This,"OnStart ()", Toast.length_short). Show ();if(!workthread.isalive ()) {Workthread.start (); } }@Override Public int Onstartcommand(Intent Intent,intFlagsintStartid) {Toast.maketext (randomservice. This,"Onstartcommand ()", Toast.length_short). Show ();return Super. Onstartcommand (Intent, flags, Startid); }@Override Public void OnDestroy() {Toast.maketext ( This,"Call OnDestroy ()", Toast.length_short). Show (); Workthread.interrupt ();Super. OnDestroy (); }PrivateRunnable backgroundwork =NewRunnable () {@Override Public void Run() {Try{ while(! Thread.interrupted ()) {Doublerandomdouble = Math.random (); Mainactivity.updategui (randomdouble); Thread.Sleep ( +); } }Catch(Interruptedexception e) {E.printstacktrace (); } } };/** * Service is called after the function is bound to return to the service object instance * / @Nullable @Override PublicIBinderOnbind(Intent Intent) {return NULL; }}
Mathservice.java (Binding method) complete code:
PackageCom.example.servicedemo;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.Binder;ImportAndroid.os.IBinder;Importandroid.support.annotation.Nullable;ImportAndroid.widget.Toast;/** * Created by Yinghao on 2016/5/6. * * Public class mathservice extends Service { /** * Use this service to obtain a service instance in a binding form */ Private FinalIBinder Mbinder =NewLocalbinder (); Public classlocalbinder extends Binder{ MathService GetService () {returnMathService. This; } }@Nullable @Override PublicIBinderOnbind(Intent Intent) {Toast.maketext (MathService). This,"Local bindings", Toast.length_short). Show ();returnMbinder; }@Override Public Boolean Onunbind(Intent Intent) {Toast.maketext (MathService). This,"Cancel local bindings: MathService", Toast.length_short). Show ();return Super. Onunbind (Intent); } Public Long Add(LongALongb) {returnA + b; }}
Mainactivity.java Complete code:
PackageCom.example.servicedemo;ImportAndroid.content.ComponentName;ImportAndroid.content.Context;ImportAndroid.content.Intent;ImportAndroid.content.ServiceConnection;ImportAndroid.os.Handler;ImportAndroid.os.IBinder;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportCOM.EXAMPLE.SIMPLERANDOMSERVICEDEMO.R; Public class mainactivity extends appcompatactivity { PrivateButton Mstartbutton;PrivateButton Mstopbutton;Private StaticTextView Mlabeltextvie;Private StaticHandler Handler =NewHandler ();Private Static DoubleRandom/** * Handler The Runnable object is passed to the interface thread's queue * so that it can update the UI */ Public Static void Updategui(Doublerefreshdouble) {random = refreshdouble; Handler.post (refreshlable); } Public StaticRunnable refreshlable =NewRunnable () {@Override Public void Run() {Mlabeltextvie.settext (string.valueof (random)); } };PrivateMathService MathService;Private BooleanIsbound =false;PrivateTextView sum;PrivateButton Bindbutton;PrivateButton Unbindbutton;PrivateButton AddButton;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);/** * Handler * * FinalIntent Intent =NewIntent ( This, Randomservice.class); Mstartbutton = (Button) Findviewbyid (R.id.start); Mstopbutton = (Button) Findviewbyid (r.id.stop); Mlabeltextvie = (TextView) Findviewbyid (R.id.tv_label); Mstartbutton.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {StartService (intent); } }); Mstopbutton.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {StopService (intent); } });/** * Bind Service * /sum = (TextView) Findviewbyid (R.id.tv_result); Bindbutton = (Button) Findviewbyid (R.id.bind); Unbindbutton = (Button) Findviewbyid (R.id.unbind); AddButton = (Button) Findviewbyid (R.id.add);FinalIntent serviceintent =NewIntent (mainactivity. This, Mathservice.class); Bindbutton.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {if(!isbound) {Bindservice (serviceintent, mconnection, context.bind_auto_create); Isbound =true; } } }); Unbindbutton.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {if(Isbound) {Unbindservice (mconnection);//If you change the above unbind to the following shutdown service, you will not be able to bind successfully again//StopService (serviceintent);MathService =NULL; Isbound =false; } } }); Addbutton.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {if(MathService = =NULL) {Sum.settext ("Unbound Service");return; }LongA = Math.Round (Math.random () * -);Longb = Math.Round (Math.random () * -);Longresult = Mathservice.add (A, b); String msg = string.valueof (a) +"+"+string.valueof (b) +"="+result; Sum.settext (msg); } }); }PrivateServiceconnection mconnection =NewServiceconnection () {@Override Public void onserviceconnected(componentname name, IBinder service) {MathService = ((mathservice.localbinder) service). GetService (); }@Override Public void onservicedisconnected(componentname name) {MathService =NULL; } };}
Local Service for Android service backend