The use of Service components in Android

As one of the four major components of Android, Service is used very frequently, and it is needed in almost every APP. It is mainly used to process business logic outside the UI, such as network requests, file downloads, monitors, and background playback. Wait for time-consuming operations or decouple business logic.

Features:

  • Runs in the background, has no user interface, and is invisible to the user.
  • It can be started by other components (such as Activity), and it will continue to run unless it is manually stopped after starting. Unless it is bound to a component, it will not stop even if the component that starts the service is destroyed.
  • Not a process, nor a thread, running on the main thread unless android: process="" is declared in the mainifest manifest.
  • There are two states of Service: startup state and binding state.
  • The priority is lower than the foreground application and higher than the background application, and it is not easy to be destroyed by the system

1. Creation of Service

**1 .** Inherit the class from Service, and override the onBind method, a basic example:

public class MyService extends Service{
    [@Override](https://my.oschina.net/u/1162528)
    public IBinder onBind(Intent intent){
        return null;
    }
}

**2 .** Register Service in AndroidManifest

<service android:name=".MyService"/>

Syntax and property declaration for Service in manifest:

<service android:enabled=["true" | "false"]
    android:exported=["true" | "false"]
    android:icon="drawable resource"
    android:isolatedProcess=["true" | "false"]
    android:label="string resource"
    android:name="string"
    android:permission="string"
    android:process="string" >
    . . .
</service>
  1. enabled: whether it can be instantiated, the default is true, otherwise it cannot be started
  2. extended: whether it can be implicitly started by other applications, the default is true
  3. icon: runtime icon
  4. isolatedPrecess: true executes in a special process, separate from other processes, and has no permissions.
  5. label: label
  6. name: Service class name
  7. permission: required permission
  8. process: when not empty, run in a separate process, prefix with ":" currently represents the package name

2. Service startup and binding

There are two ways to start a Service:

The startService method starts the service

void Context.startService(Intent intent)

After the service is started by this method, the service is not associated with the life cycle of the started component, even if the component that started the service has been destroyed, the service continues to execute indefinitely until it is killed by the system, or manually call the code context.stopService() or in the Service internally calls stopSelf().

The bindService method starts the service

After setting the process attribute in the manifest, the service is not in the same check, the bound service will not be able to get the callback IBinder

void Context.bindService(Intent intent, ServiceConnection conn, int flag)

After this method starts the service, the service is associated with the life cycle of the component that started the service. If the component that started the service is destroyed, the service is also destroyed. When multiple components are bound, all components are destroyed, and the service is destroyed.

This method passes in three parameters, the first is the intent to start the service, the second is the object that implements the ServiceConnection interface, and the third is the startup method

The second parameter ServiceConnection interface is as follows:

public interface ServiceConnection {

    void onServiceConnected(ComponentName var1, IBinder var2);
    // 与服务绑定成功后回调, ComponentName 为组件名称, IBinder 为服务 onBind 方法返回的 Binder
    void onServiceDisconnected(ComponentName var1);
    // 与服务解绑后回调
    default void onBindingDied(ComponentName name) {
    // 与服务绑定失败后回调
    }
}

The third parameter, startup method:

Service.BIND_AUTO_CREATE As long as the binding exists, the service will be created automatically. Otherwise, only the binding will not start the service, and the service will continue to be bound when the service is subsequently started.

Service.BIND_NOT_FORGROUND does not allow binding to elevate the service's process to the foreground scheduling priority.

Service.BIND_ABOVE_CLIENT Service is more important than bound component

Service.BIND_WAIVE_PRIORITY Do not affect the scheduling or memory management priority of the service's managed process

3. Service life cycle

Start through the startService method: onCreate -> onStartCommand -> onDestroy

Started by bindService method: onCreate -> onBind -> onUnbind -> onDestroy

Sample code:

public class MyService extends Service{
    // 当通过 bindService 与组件绑定时调用
    public IBinder onBind(){
        return null;
        //return new MyBinder();
    }  
    // 被第一次被创建时调用, 服务在运行则不调用
    public void onCreate(){
        super.onCreate();
    }
    // 调用 startService() 方法都会被回调, bindService() 方法不回调
    public int onStartCommand(Intent intent, int flags, int startId){
       return super.onStartCommand(intent, flags, startId);  
    }
    // 被销毁时回调
    public void onDestroy(){
        super.onDestroy();
    }
    // 用户自定义的 IPC 通信的 Binder, 实例化后在 onBind 中返回给调用 bindService 的组件
    class MyBinder extends Binder{
        public MyService getService(){
            //返回 服务 实例, 供其他组件调用服务方法
            return MyService.this;
        }
    }
}

The onStartCommand() method returns an int data to describe what to do when the system destroys the service

START_NOT_STICKY : do not restart after destruction

START_STICKY : Automatic restart after destruction, intent = null

START_REDELIVER_INTENT : Restart after destruction

4. Communicate with Service

Binder bindService default

This method must call bindService

Define a class in Service to inherit Binder, return the instance of this class in onBind, and implement the ServiceConnection interface in the component that binds the service. When the service is bound successfully, the Binder instance will be returned and onServiceConnected will be called back

method, just cast IBinder to Service.Binder,

public class MyService extends Service{
    public IBinder onBind(){
        return new MyBinder();
    }
    class MyBinder extends Binder{
        public MyService getService(){
            return MyService.this;
        }
    }
}

public class MyActivity extends AppcompactActivity implements ServiceConnection{
    Binder binder = null;
    ...
    public void onServiceConnected(ComponentName var1, IBinder var2){
        this.binder = (MyServic.MyBinder)IBinder;
        binder.getService();
    }
}

Messager cross-process, safe, non-concurrent

Broadcast, convenient

AIDL

(over)

Blog link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325022789&siteId=291194637