Comparison of Android Service startup methods (1)

Service brief introduction:

A service is an application component that performs long-running operations in the background and provides no user interface. An application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can be bound to a service to interact with it and even perform inter-process communication (IPC). For example, a service might handle network communications, play music, time operations, or interact with a content provider, all performed in the background.

Kind of service

  • Sort by location
category the difference advantage shortcoming application
Local Service The service is attached to the main process The service is attached to the main process instead of an independent process, which saves resources to a certain extent. In addition, the Local service does not need IPC or AIDL because it is in the same process. Corresponding bindService will be much more convenient After the main process is Killed, the service will be terminated. Such as: music player playback and other services that do not require permanent residence.
Remote Service The service is an independent process The service is an independent process, and the corresponding process name format is the package name plus the android:process string you specify. Because it is an independent process, when the process where the Activity is located is Killed, the service is still running and is not affected by other processes, which is conducive to providing services for multiple processes and has high flexibility The service is an independent process, it will take up a certain amount of resources, and it is a little more troublesome to use AIDL for IPC Some services that provide system services are resident.
  • Sort by run type
category the difference application
Reception The notification of onGoing will be displayed in the notification bar When the service is terminated, the Notification in the notification column will also disappear, which has a certain notification effect for the user. Common such as music playback services.
Background Services The default service is the background service, that is, the onGoing Notification will not be displayed in the notification column. When the service is terminated, the user will not see the effect. Certain services that do not require prompts to run or terminate, such as weather updates, date synchronization, mail synchronization, etc.
  • Sort by usage
category the difference
service started by startService Mainly used to start a service to perform background tasks without communication. To stop a service use stopService.
Services started by bindService The default service is the background service, that is, the onGoing Notification will not be displayed in the notification column.
Services started using startService and bindService at the same time To stop a service, both stopService and unbindService should be used

service life cycle

Life cycle comparison under different startup modes

Through this figure, we can see the comparison between the two startup methods and their life cycles. The start service mainly calls the onStartCommand() method to process the logic. The bind service mainly calls the onBind() method to process the logic, and uses the onUnbind() method to unbind, and the service will be killed.

We just need to know that no matter how the service is started, the onCreate() life cycle will only be executed once

  1. After startService establishes a connection, the onBind() life cycle will never be called anyway. When the app is closed and the service is not stopped, it will be kept in the background until stopService or stopSelf of the Service itself is called to stop the service.
  2. After bindService establishes a connection, the onStartCommand() life cycle will not be called. The onUnbind() life cycle will be automatically called after the app is closed by executing unBindService() to unbind the service. Its startup cycle depends on the Context that started it. If the Service is not stopped , will report an exception error
Notice:
  1. When the screen of the mobile phone is rotated, if the Activity is set to rotate automatically, the Activity will be recreated during the rotation process. If the connection is established with bindServie, the service will be disconnected (the previous Context does not exist), and the service will be disconnected. will be automatically stopped
  2. If you use the startService and bindService methods to start the Service at the same time, when you need to terminate the Service, you need to call the stopService and unbindService methods (unbindService is attached to the Context that started it, and startServicec is not attached to the Context that started it. If you call unbindService first, then the service will not It will not be terminated. When stopService is called, the service will be terminated; if stopService is called first, the service will not be terminated. When unbindService is called or the Context that previously called bindService no longer exists (such as Activity is finished), the service will not be terminated. will stop automatically);
  3. When you need to stop the service, it is best to stop the service in the onDestory() of the Activity

use

1. After creating a new Serivice, first register the Service in AndroidManifest.xml, and add the Service information that needs to be registered in the application:

        <service android:name=".TestService" >
            android:exported="true" 
        </service>

2. There are two startup methods in the Service file

public class TestService extends Service{

    @Override
    public void onCreate() {
        super.onCreate(); 
    } 

    /** 
    * onBind 是 Service 的虚方法,因此我们不得不实现它。
    * 返回 null,表示客服端不能建立到此服务的连接。
    */ 
    @Override
    public IBinder onBind(Intent intent) { 
        return new MyBinder();
    }

    // 已取代onStart方法--onStart方法是在Android2.0之前的平台使用的.
    // 在2.0及其之后,则需重写onStartCommand方法,同时,旧的onStart方法则不会再被直接调用
    // (外部调用onStartCommand,而onStartCommand里会再调用 onStart。在2.0之后,
    // 推荐覆盖onStartCommand方法,而为了向前兼容,在onStartCommand依然会调用onStart方法。
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(tag, "自启动的flags"+flags+"       启动的strtId"+startId);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);//休眠三秒===模仿耗时操作
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String str=intent.getStringExtra("name");
                Log.e(tag, str);
            }
        }).start();
        return START_REDELIVER_INTENT;
    } 

    @Override
    public boolean onUnbind(Intent intent) { 
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy(); 
    } 
    // IBinder是远程对象的基本接口,是为高性能而设计的轻量级远程调用机制的核心部分。但它不仅用于远程
    // 调用,也用于进程内调用。这个接口定义了与远程对象交互的协议。
    // 不要直接实现这个接口,而应该从Binder派生。
    // Binder类已实现了IBinder接口
    class MyBinder extends Binder { 
        /** 
        * 获取Service的方法
        * @return 返回TestService
        */ 
        public  TestService getService(){
            return TestService.this;
        }
    }
}

3.start startup method

public class TestActivity extends Activity{
  private Intent intent;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    intent = new Intent(this, TestSerice.class);
    intent.putExtra("name", "启动了service");
    startService(intent);// 启动服务
  }
  @Override
  protected void onDestroy() {
    super.onDestroy();
    stopService(intent);// 在退出Activity时停止该服务
  }
}

4.bind startup method

1). Local binding

public class TestActivity extends Activity{
   @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, TestService.class);
    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);//绑定目标Service
  }
  @Override
  protected void onDestroy() {
    super.onDestroy();
    unbindService(serviceConnection);// 解除绑定,断开连接
  }
  // 在Activity中,我们通过ServiceConnection接口来取得建立连接与连接意外丢失的回调
  ServiceConnection serviceConnection = new ServiceConnection() {            @Override
    public void onServiceConnected(ComponentName name, IBinder service){
      // 建立连接
      // 获取服务的操作对象
               TestService.MyBinder binder = (TestService.MyBinder)service;
               binder.getService();// 获取到的Service即TestService
    } 
    @Override
    public void onServiceDisconnected(ComponentName name) {
      // 连接断开
    }
  };
}

2). Remote binding

Common attributes of Service element in AndroidManifest.xml

  • andorid:name: Service class name. Can be the full package name + class name. You can also use . instead of the package name.
  • adroid:exported: Whether other applications can access the service, if not, only this application or applications with the same user ID can access. Defaults to false.
  • android:enabled: The service name displayed to the user. If no service name is set, the class name of the service is displayed by default.
  • android:process : The name of the process the service is running on. The default is to run under the current process, which is consistent with the package name. If set, the package name will be appended with the set integration name. If the name is set to start with a colon :, a new process private to the application will be created when needed and run to this process. If the name starts with a lowercase letter, the service will run in a global process with the same name, if it has permission to do so. This allows components of different applications to share a process, reducing resource usage.
  • android:icon : The icon for the service.
  • android:permission: Apply for permission to use the service. If the relevant permissions are not configured, the service will not be executed, and the startService() and bindService() methods will not be executed.

Guess you like

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