service---七月十九号实验

service---七月十九号实验

1 startService、bindService

  1. startService:即使用户不直接与应用程序交互做的事情。这对应于Context.startService()系统安排服务工作的调用 ,直到服务或其他人明确停止它为止。,

  2. bindService:Context.bindService(),它允许与服务建立长期连接以便与服务进行交互。

2 分析生命周期变化

生命周期:

上图中onStart()方法已经弃用;

流程:onCreat—》onStartCommand--》onBind--》onUnbind--》onDestroy

系统可以运行服务有两个原因。

  1. 如果有人调用,Context.startService()那么系统将启动服务(创建它并onCreate()在需要时调用其方法),然后onStartCommand(Intent, int, int)使用客户端提供的参数调用其方法。此服务将在此时继续运行,直到Context.stopService()或被 stopSelf()调用。请注意,对Context.startService()的多次调用不会嵌套(尽管它们会导致多次对onStartCommand()的相应调用),因此无论启动多少次,一旦Context.stopService()或stopSelf停止服务 ; 服务可以使用它们的stopSelf(int)方法来确保在处理启动的意图之前不停止服务。

  2. 对于已启动的服务,他们可以决定运行两种主要的操作模式,具体取决于它们从onStartCommand()返回的值:START_STICKY用于根据需要显式启动和停止的服务,同时START_NOT_STICKYSTART_REDELIVER_INTENT用于服务应该只在处理发送给它们的任何命令时保持运行。。

客户端还可以Context.bindService()用于获取与服务的持久连接。如果服务尚未运行(onCreate()在执行此操作时调用),这同样会创建服务,但不会调用onStartCommand()。客户端将接收IBinder服务从其onBind(Intent)方法返回的 对象 ,允许客户端然后回调该服务。只要建立连接,服务将保持运行(客户端是否保留对服务的IBinder的引用)。通常,IBinder返回的是一个用aidl编写的复杂接口。

通过Demo类继承Service , 实现关于生命周期的方法,新建Activity来调用Service的方法:

  1.  @Override
        public void onCreate() {
            Log.d("Service声明周期", "onCreate: ");
            super.onCreate();
        }
    
        @Override
        public ComponentName startService(Intent service) {
            Log.d("Service声明周期", "startService: ");
            return super.startService(service);
        }
        
        @Override
        public IBinder onBind(Intent intent) {
            Log.d("Service声明周期", "onBind: ");
            return null;
        }
        @Override
        public void onRebind(Intent intent) {
            Log.d("Service声明周期", "onRebind: ");
            super.onRebind(intent);
        }
    
        @Override
        public void onDestroy() {
            Log.d("Service声明周期 ","onDestroy: ");
            super.onDestroy();
        }
    
    

启动验证周期:

相关链接:

  1. 官网:https://developer.android.com/reference/android/app/Service.html?hl=en#ProcessLifecycle

问题思考:

1. onBind方法返回值为IBinder,starService返回为ComponentName:

2. onStart()方法已经弃用;使用:ComponentName startService(Intent service)

3.使用: 继承Binder,建立对象, onBind方法返回IBind对象,传入OnServiceConnection方法。

原文地址:https://www.cnblogs.com/liguo-wang/p/11214602.html