Four major components of Android-Background operations using services and four major components of android
What is a service?
A service is a component without a visual interface. It can run and perform various operations in the background for a long time.
Service creation
We only need to inherit the Service class and implement the corresponding method to create the Service.
To start the service, you must register the service in AndroidManifest.
Sample Code of the service class
Package com. whathecode. servicedemo; import android. app. service; import android. content. intent; import android. OS. IBinder; import android. widget. toast; public class ExtendsionService extends Service {/*** this method is called when the Service is created for the first time */@ Overridepublic void onCreate () {super. onCreate (); Toast. makeText (getBaseContext (), "service created", Toast. LENGTH_SHORT ). show ();}/*** this method is called when the service is started using the startService Method */@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {Toast. makeText (getBaseContext (), "service started", Toast. LENGTH_SHORT ). show (); return super. onStartCommand (intent, flags, startId) ;}@ Overridepublic IBinder onBind (Intent intent) {return null ;}@ Overridepublic void onDestroy () {super. onDestroy ();}}
Start the service using startService
Logic code of the main interface:
Package com. whathecode. servicedemo; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; public class MainActivity extends Activity {Intent service = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // create a service = new Intent (this, ExtendsionService. class);} public void start (View view) {// start the service startService (service);} public void stop (View view) {// stop service (service );}}
Registration Service:
<service android:name="com.whathecode.servicedemo.BackgroundService"></service>
Running effect:
Note:
When we click the Start Service button for the first time, the onCreate method and the onStartCommand method are executed in sequence,
However, when you click the Start Service button for the second time, the service is already running and the onCreate method is no longer executed for the second time,
The onStartCommand method is always executed when startService is called to start the service.
The onDestroy method is executed after the stopService method is called.
In addition to starting the service using the startService method, we can also start the service using the Bind method.
The difference between the former and the latter is:
The service life cycle does not depend on the starter. After the service is started, it runs in the background until the stopService call is stopped.
The Bind method is used to start the service. The service life cycle depends on the starter. That is, the service is automatically destroyed after the initiator exits.
Start the service in Bind Mode
The bindService method is used to start the service and the unbindService method is used to destroy the service.
The advantage of using this method to start the service is that when the bind is successful, the service returns an IBinder object,
We can implement this object in the service class to access the specific methods in the service.
To achieve the purpose of communication with the service.
Note:
We cannot directly instantiate the service to call the methods in it.
In addition:
If you do not unbind it when you exit the service, the program will throw an IllegalArgumentException exception.
Therefore, you must use unbindService to unbind the service after you call bindService to start the service.
Sample Code:
Package com. whathecode. servicedemo; import android. app. activity; import android. content. componentName; import android. content. intent; import android. content. serviceConnection; import android. OS. bundle; import android. OS. IBinder; import android. view. view; public class MainActivity extends Activity {Intent service = null; IReceptionist rpst;/*** parameters used by bindService and unbindService */serviceprivate connection conn = new ServiceConnection () {// this method is called when the service connection is accidentally terminated. @ Overridepublic void onServiceDisconnected (ComponentName) {} // This method is automatically called when the service is connected, the second parameter is the object returned in the onBind method of the service class @ Overridepublic void onServiceConnected (ComponentName name, IBinder service) {rpst = (IReceptionist) service; rpst. callExtendsionNumber () ;}}; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // create a service = new Intent (this, ExtendsionService. class);} public void start (View view) {// start the service startService (service);} public void stop (View view) {// stop the service stopService (service );} public void bind (View view) {// bindService (service, conn, BIND_AUTO_CREATE);} public void unBind (View view) {// unbind service unbindService (conn );}}
Inherit the ServiceBinder object and implement the custom interface:
In this way, we can expose only required methods to implement code protection.
IReceptionist interface code:
package com.whathecode.servicedemo;public interface IReceptionist {public void callExtendsionNumber();}
Code of the ExtendsionService class:
Package com. whathecode. servicedemo; import android. app. service; import android. content. intent; import android. OS. binder; import android. OS. IBinder; import android. util. log; import android. widget. toast; public class ExtendsionService extends Service {private static final String TAG = "ExtendsionService";/*** call this method when the Service is created for the first time */@ Overridepublic void onCreate () {super. onCreate (); Toast. makeText (getBaseContext (), "service created", Toast. LENGTH_SHORT ). show ();}/*** this method is called when the service is started using the startService Method */@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {Toast. makeText (getBaseContext (), "service started", Toast. LENGTH_SHORT ). show (); return super. onStartCommand (intent, flags, startId) ;}@ Overridepublic IBinder onBind (Intent intent) {return new ServiceBinder () ;}@ Overridepublic void onDestroy () {Toast. makeText (getBaseContext (), "the service is destroyed", Toast. LENGTH_SHORT ). show (); Log. d (TAG, "Service destroyed"); super. onDestroy ();} public void putExtendsion () {Toast. makeText (getBaseContext (), "transferring extension for you", Toast. LENGTH_SHORT ). show ();} /***** inherit from the Binder and implement the IReceptionist interface * inherit from the Binder class. This type of object needs to be returned in the onBind method ** implement the IReceptionist interface as the need to expose the Method */private class ServiceBinder extends Binder implements IReceptionist {public void callExtendsionNumber () {putExtendsion ();} private void otherMethod (){}}}
Running effect:
Note: When you press the return key, the Activity is destroyed and the services started by the Activity are also destroyed.
This kind of service seems to have little effect. Is there a way to quit the service when you exit the Activity?
The answer is yes: Android allows us to activate a service first and then call bindService to bind it to the service,
In this way, we can achieve the purpose of communication with the service, but also make the service run in the background for a long time.
See:
The following figure shows how the above Code works: