Two ways to open the service of Android four components:
- StartService (); Turn on the service.
After the service is turned on, the service will run in the background for a long time, even if the caller exits. The service continues to run in the background. The service is not related to the caller, and the caller is not allowed to access the method inside the service.
- Bindservice (); Bind service.
When the service is turned on, the life cycle is associated with the caller. The caller hangs up and the service hangs up. Not to be born at the same time, but to die at the same time. The caller and the service are bound together, and callers can indirectly invoke methods inside the service.
Aidl
Local Service: Service code in this application
Remote service: The service is inside another application (another process inside)
Aidl:android Interface Defination Language
IPC Implementation:inter Process Communication
The life cycle of a service mix call
Turn on the service and then go to bind the service and then stop the service, then the service is unable to stop. You must first unbind the service and then stop the service, which is often used in real-world development, to open the service (to ensure long-term background operation of the service) –> bind service (the method that invokes the service) –> Unbind service ( Service continues to run in the background) –> stop service (service stop), the service will only be opened once, if it has been turned on to perform the open operation is not effective.
The principle of the binding service invocation method
- Define an interface that defines a method
publicinterface IService { publicvoidcallMethodInService();//通过该类中提供一个方法,让自定 义的类实现这个接口 }
- In the service to customize a IBinder implementation class, let this class inherit binder (Binder is the default adapter of IBinder), because this custom class is private, in order to get the class in other classes, we need to define an interface, provide a method, Let the IBinder class implement the interface and invoke the method in the appropriate method for others to invoke.
Public class testservice extends Service { @Override PublicIBinderOnbind(Intent Intent) {System.out.println ("Onbind");return NewMybinder (); }Private class mybinder extends Binder implements IService{ Public void Callmethodinservice(){//Implement the method to invoke the method in the serviceMethodinservice (); } }//methods in the service Public void Methodinservice() {Toast.maketext ( This,"I am the service inside the spring elder brother, Barabula!",0). Show (); } }
- The invocation class of the service
onServiceConnected
strongly turns the second argument in the method into an interface
Public class demoactivity extends Activity { PrivateIntent Intent;PrivateMyConn Conn;PrivateIService IService;@Override Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Intent =NewIntent ( This, Testservice.class); Setcontentview (R.layout.main); } Public void Start(View view) {StartService (intent); } Public void Stop(View view) {StopService (intent); } Public void Bind(View view) {conn =NewMyConn ();//1. The binding service passes a Conn object. This conn is a callback interface.Bindservice (Intent, Conn, context.bind_auto_create); } Public void Unbind(View view) {Unbindservice (conn); }//Invoke methods in the service Public void Pager(View view) {Iservice.callmethodinservice (); }Private class myconn implements serviceconnection{ //method that is called when the service is successfully bound. @Override Public void onserviceconnected(componentname name, IBinder service) {//The second parameter is the return value of the Onbind method in the serviceIService = (iservice) service; }@Override Public void onservicedisconnected(componentname name) { } } }
Remote Service Aidl
The principle of the method in the binding service invocation service is described above, as is the binding for remote services.
But this remote service is in another program, the interface defined in another program,
Not in another program, even if we define an exact same in our own application.
interface, but due to the different registration of the two programs, the two interfaces are not the same, in order to solve this
Problem, Google's engineers gave the aidl, and we will define this interface to .java
change .aidl
,
Then remove all of this interface 权限修饰符
and copy the Aidl in another program.
In the same package name, because the Android
application is distinguished by the package name, the two
aidl
Package name, the system considers the interface in both programs to be the same, so that it can be in another
A program to turn the parameters into this interface, after the use aidl
of files copied to their own project will automatically
Generates an interface class that has an inner class that Stub
inherits Binder
and implements the
This interface, so we IBinder的实现类
only need to let the custom class inherit Stub类
when customizing
Can.
- Define an interface in the remote service and change it to
aidl
package com.seal.test.service; interface IService { void callMethodInService(); }
- Define one in the remote service
Ibinder的实现类
, let the implementation class inherit the above interface Stub类
,
and onBind
return this custom class object in the method
Public class remoteservice extends Service { @Override PublicIBinderOnbind(Intent Intent) {System.out.println ("Remote service is bound");return NewMybinder (); }Private class mybinder extends iservice. Stub { @Override Public void Callmethodinservice() {methodinservice (); } } Public void Methodinservice() {System.out.println ("I'm the method inside the remote service."); } }
- In other programs, when you want to bind the service and call the methods in this service, first copy
This aidl
file into your own project, and then ServiceConnection
the implementation class will make this parameter
asInterface
by means of a method, the interface is then obtained, and the method in the interface is called.
Public class callremoteactivity extends Activity { PrivateIntent Service;PrivateIService IService;@Override Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main); Service =NewIntent (); Service.setaction ("Com.itheima.xxxx"); } Public void Bind(View veiw) {Bindservice (service,NewMyConn (), bind_auto_create); } Public void Pager(View view) {Try{Iservice.callmethodinservice (); }Catch(RemoteException e) {E.printstacktrace (); } }Private class myconn implements serviceconnection{ @Override Public void onserviceconnected(componentname name, IBinder service) {IService = IService.Stub.asInterface (service); }@Override Public void onservicedisconnected(componentname name) {//TODO auto-generated method stub} } }
Finally, say IntentService
:
IntentService
is a Service
subclass that is used to handle asynchronous requests. The client can pass startService(Intent)
the requested delivery request by means of a method Intent
IntentService
,
IntentService
will be Intent
added to the queue, then each one Intent
is opened for worker thread
processing, after all the work is done automatically stop Service
.
Each request is processed in a separate worker thread
process and does not block the main thread of the application. In IntentService
fact Looper
, Handler
Service
The aggregate, he has not only the function of service, but also the function of processing and looping messages.
- Service:
- A Service is not a separate process. The Service object itself does not imply it was running in its own process; Unless otherwise specified, it runs in the same process as the application it was part of.
- a Service is not a thread. It is a means itself to does work off of the main thread (to avoid application not responding errors).
so the time-consuming operation in Service
requires a new thread to be opened.
As to why you should use service
instead of Thread
, the main difference is that the lifecycle is different, and Service
is a component of the Android system. The Android system will try to keep the service
running in the long run, and
will revive the service when memory is available, even if it kills the service (less memory is not enough to kill the service), and Thread
will be killed later
- intentservice
- Intentservice is a base class for Services that handle asynchronous requests (expressed As Intents) on demand. Clients send requests Throughstartservice (Intent) calls;
The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
- This "Work queue processor" pattern was commonly used to offload the tasks from a application ' s main thread. The Intentservice class exists to simplify this pattern and take care of the mechanics.
to use it, extend Intentservice and implement Onhandleintent (Intent). Intentservice would receive the Intents, launch a worker thread, and stop the service as appropriate.
- all requests is handled on a single worker Thread–they could take as long as necessary (and would not block the Applic Ation ' s main loop), but only one request would be processed at a time.
- Email: [Email protected]
- Good luck!
Service of Android four components