Four components - Service life cycle

[Service life cycle]

0. Service life cycle and two startup methods.

  • startService Start service: used to start a service to perform background tasks, stop the service using stopService().

  • bindService start service: start service for communication, stop service use unbindService().

x

  • startService / stopService

      onCreate() -> onStartCommand() -> onDestroy()
      第一次调用会触发 onCreate() 和 onStartCommand,之后每次启动服务只触发 onStartCommand()
      无论 startService 多少次,stopService 一次就会停止服务
    
  • bindService/unbindService

      onCreate() -> onBind() -> onUnbind() -> onDestroy()
      第一次 bindService 会触发 onCreate() 和 onBind(),若不unBind() 则以后每次 bindService 都不会调用任何生命周期方法。
      bindService 启动的生命周期依附于启动它的 Context
    

0.1 The onRebind method in Service is called, it must meet two necessary conditions

  1. The return value of the onUnBind method in the service is true
  2. The service object is not destroyed after being unbound, and then bound again

0.2 Need to pay attention to a problem:

当Activity退出的时候,Sercvice并不会停止,此时我们可以再进入Activity重新绑定,当这时候 Service就会调用onRebind()方法,但是调用onRebind()方法的前提是先前的onUnbind()方法执行成功,但是使用 super.onUnbind(intent)是执行不成功的,

这时候我们要手动的使其返回true,再次绑定时Rebind()就会执行。否则,如果退出时不显示的指定onUnbind()为成功的话(为false),那么重新启动此Activity来绑定服务时,Service的onBind()方法和onReBind都不会执行,但是ServiceConnection方法确一定会回调了。这说明在Service中的onBind()方法不同于 onStart()方法不能被重复调用。

The source code is as follows:

  /**
     * Called when all clients have disconnected from a particular interface
     * published by the service.  The default implementation does nothing and
     * returns false.
     * 
     * @param intent The Intent that was used to bind to this service,
     * as given to {@link android.content.Context#bindService
     * Context.bindService}.  Note that any extras that were included with
     * the Intent at that point will <em>not</em> be seen here.
     * 
     * @return Return true if you would like to have the service's
     * {@link #onRebind} method later called when new clients bind to it.
     */
    public boolean onUnbind(Intent intent) {
    
    
        return false; //默认返回 FALSE ,因此如果想要 onRebind()可以被调用,则子类需要重写此方法。
    }

1. According to the different opening methods, it is divided into two life cycles

The life cycle of Service, from its creation to its destruction, can have two different paths:

  • onCreate();

    • Called when the service is started for the first time (when the startService method is called for the second time, the onStartCommand is called directly instead of the onCreate method)
  • onBind(); //When the bindService(…) method is called for the first time, onCreate is first called and then the onBind method is called. Indicates that the service has been bound—[bind mode is unique to open services]

    • When the bindService method is called, if the Service has already been created (onCreate), it will directly call onBind for binding instead of recreating: - mixed method
  • onStartCommand();

    • or onStart(); (obsolete), this method will be called when the service starts. After it is turned on, you can see it in Settings>>Application Management>>Running
  • onUnbind();

    • This method is called whenever a client unbinds from the Service.
  • onDestroy() ;

    • Called when the service is destroyed. (After calling methods such as stopService(), or the user manually sets shutdown, or all clients are unbound from this Service)

2. [There are two ways to open the service]: ----[And the two opening methods correspond to two life cycles respectively]

  • Method 1: [Open] context.startService(); ----[Close] context.stopService(). or stopSelf()

    Features:
    1.【startService: The service started by the method will run in the background for a long time, until the stopService() and other methods are called, or the user manually sets the shutdown】

      2.【客户端不能与Service进行通信(即:客户端不能对Service进行控制)】
    
  • Method 2: [Open] context.bindService(); -----[Close] context.unbindService(). or stopSelf()

    • Features:
      1. [Using bind to open the service, you must manually unbind (unbindService) when the client (ie: component (such as: Activity)) exits, otherwise an error will be reported (leakage)] ------- (similar to
        dynamic Registered broadcast receiver: the registration must be unregistered before the program exits, otherwise an error will be reported)

         因此建议在客户端(组件)的onDestroy方法中 取消绑定(unbindService) ,但若不取消绑定实际上也会销毁服务	
        
      2. [The client can obtain an instance that implements the IBinder interface to communicate with the Service. (The client calls the method in the Service)]

      3. [A service can be bound to multiple clients at the same time. When multiple clients are unbound (unBindService()), the service can be called and destroyed]

      4. [Services opened by bind: cannot be seen in Settings >> Application Management >> Services, so it is equivalent to an invisible service]

  • [Service of the first opening method] -----startService

    1. The started service is called by other components [startService() is created].

    2. This service can run indefinitely, and must call the stopSelf() method or other components call the stopService() method to stop it.

    3. When the service is stopped, the system destroys it.

  • [Service of the second opening method]----bindService

    1. The bound service is created when another component (a client) calls [bindService()].

2. [The client can obtain an instance that implements the IBinder interface to communicate with the Service. (The client calls the method in the Service to control the Service)]

3. The client can close this connection through the unbindService() method.

4. [A service can be bound to multiple clients at the same time, and the system will destroy the service only after multiple clients are unbound (unBindService())]

  • [You can also start the Service in a mixed way]

That is to say: [Services opened by startService can also be bound using bindService]

* For example: a background music service may be started by calling the startService() method,

		稍后可能用户想要控制播放器或者得到一些当前歌曲的信息,可以通过bindService()将一个activity和service绑定。

* 【注意】:这种情况下,[stopService()或 stopSelf()实际上并不能停止这个service,除非所有的客户都先解除绑定unBindService()]

	* 【因此:混合方式开启的Service,在需要关闭时必须 先解绑(unBindService)所有客户,后停止服务(stopService()或 stopSelf())】	

3. Implementing the lifecycle callbacks

Like activity, service also has a series of life cycle callback functions, which you can implement to monitor service state changes and perform appropriate work at the appropriate time.

public class ExampleService extends Service{
    
    

    int mStartMode; // indicates how to behave if the service is killed
    IBinder mBinder; // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used

    @Override
    public void onCreate() {
    
    
        // The service is being created
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
    
        // The service is starting, due to a call to startService()
        return mStartMode;
    }

    @Override
    public IBinder onBind(Intent intent) {
    
    
        // A client is binding to the service with bindService()
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent){
    
    
        // All clients have unbound with unbindService()
        return mAllowRebind;
    }

    @Override
    public void onRebind(Intent intent) {
    
    
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }

    /**
     * 强烈建议在Service的onDestroy()方法里去清理掉那些不再使用的资源,防止在Service被销毁后还会有一些不再使用的对象仍占用着内存
     */
    @Override
    public void onDestroy(){
    
    
        // The service is no longer used and is being destroyed
    }
}
  • [Unlike the life cycle callback function of activity, you don't need to call the implementation of the base class. You can also call]

——————————————————————————————————————————————————————————————————————————————————

4: Service life cycle diagram:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-iqefyI1R-1677227783916) (Service life cycle diagram.png)]

This figure illustrates the typical callback method of a service, although this figure separates the opened service from the bound service,

[But it needs to be remembered that any service potentially allows binding. Therefore, a service that is enabled may still be bound.

  • Implement these methods, you can see the life cycle of the two-layer nested service: ----- (the life time of the overall life time nested activity)

    The entire lifetime ([overall life time])

    The overall life time of the service is from when onCreate() is called until the onDestroy() method returns.

    Like activity, service performs its initialization in onCreate() and releases remaining resources in onDestroy().

    For example, a music playback service can create a music playback thread in onCreate() and stop the thread in onDestory().

    onCreate() and onDestroy() will be called by all services, regardless of whether the service is created through startService() or bindService().

    The active lifetime (【Active Lifetime】)

    The active lifetime of the service is from when onStartCommand() or onBind() is called, and
    they respectively process the Intent object passed by the startService() or bindService() method.

    If the service is started with startService(), then its active life cycle ends with the entire life cycle.

    If the service is bound with bindService(), its activity lifecycle ends after the onUnbind() method returns.

* Note: Although an opened service is stopped by calling stopSelf() or stopService(), there is no corresponding callback function corresponding to it, that is, there is no onStop() callback method.

	* 所以,当调用了停止的方法,除非这个service和客户组件绑定,否则系统将会直接销毁它,onDestory()方法会被调用,并且是这个时候唯一会被调用的回调方法。

5. Life cycle management of Service opened in binding form

When the bound service and all clients are unbound, the Android system will destroy it (unless it is also opened by the onStartCommand() method).

Therefore, if your service is a purely bound service, then you don't need to manage its lifecycle.

However, if you choose to implement the onStartCommand() callback method, then you must explicitly stop the service, because the service is considered to be started at this time.

In this case, the service will run until it calls stopSelf() or another component calls stopService(), regardless of whether it is bound to the client or not.

In addition, if your service is enabled and accepts bindings, when the system calls your onUnbind() method, if you want to accept an onRebind() call the next time the client binds (instead of calling onBind( )), you can choose to return true in onUnbind().

The return value of onRebind() is void, but the client still gets the IBinder object in its onServiceConnected() callback method.

————————————————————————————————————————————————————————————————————————————————————————

6. [A relatively standard Service can be written as:]

	public class ExampleService extends Service{
    
    

		    IBinder mBinder; // interface for clients that bind

		    @Override
		    public void onCreate() {
    
    
		        // The service is being created
		    }

			@Override  
			public int onStartCommand(Intent intent, int flags, int startId) {
    
      
			    new Thread(new Runnable() {
    
      
			        @Override  
			        public void run() {
    
      
			            // 开始执行后台任务  
			        }  
			    }).start();  
			    return super.onStartCommand(intent, flags, startId);  
			}  
			  
			class MyBinder extends Binder {
    
      
			  
			    public void startDownload() {
    
      
			        new Thread(new Runnable() {
    
      
			            @Override  
			            public void run() {
    
      
			                // 执行具体的下载任务  
			            }  
			        }).start();  
			    }  
			} 
    }	 		

Attached:

  • A service can be bound multiple times, but can only be unbind once.

  • Unbind services cannot be unbind.

Guess you like

Origin blog.csdn.net/UserFrank/article/details/129203913