Introduction to Android Development_ DAY7

Posted by bgoulette612 on Sun, 06 Mar 2022 10:58:41 +0100

07

Service

I Related concepts of thread

  • Program: a set of instructions (a set of static code) written in a language to complete a specific task
  • Process: the running program is an independent unit of system scheduling and resource allocation. The operating system will allocate a section of memory space for each process! The dynamic execution of the program in turn goes through the complete process of loading, executing and executing the code!
  • Thread: an execution unit smaller than a process. Each process may have multiple threads. Threads need to be placed in one process to execute. Threads are managed by the program, and processes are scheduled by the system!
  • Understanding of multithreading: multiple instructions are executed in parallel, and the CPU time slice is allocated to each thread according to the scheduling algorithm. In fact, it is executed in time-sharing. However, the switching time is very short, and the user feels "at the same time"!

II Thread life cycle

III Method of creating thread

  1. Inherit Thread class
public class MyThread extends Thread{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        //super.run();
        doSomething();
    }
    private void doSomething() {
        // TODO Auto-generated method stub
        System.out.println("I am a method in a thread");
    }
}
===================================================================
===============
public class NewThread {
    public static void main(String[] args) {
    MyThread myThread=new MyThread();
    myThread.start();//Open a thread method
        //The following methods can be executed concurrently with the thread above
        doSomething();
    }
    private static void doSomething() {
        // TODO Auto-generated method stub
    }
}

  1. Implement Runnable interface
public class RunnableThread implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        doSomeThing();
    }
    private void doSomeThing() {
    // TODO Auto-generated method stub
    System.out.println("I am a thread method");
    }
}
===================================================================
===============
public class NewThread {
    public static void main(String[] args) {
        Runnable runnable=new RunnableThread();
        Thread thread=new Thread(runnable);
        thread.start();//Open a thread method
        //The following methods can be executed concurrently with the thread above
        doSomething();
    }
    private static void doSomething() {
        // TODO Auto-generated method stub
    }
}
  1. Implement Callable interface and Future creation thread
public class CallableThread implements Callable<String>{
    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        doSomeThing();
        return "Value to return";
    }
    private void doSomeThing() {
        // TODO Auto-generated method stub
        System.out.println("I am the method in the thread");
    }
}
===================================================================
===============
public class NewThread {
    public static void main(String[] args) {
        Callable<String> callable=new CallableThread();
        FutureTask<String> futureTask=new FutureTask<String>
(callable);
        Thread thread=new Thread(futureTask);
        thread.start();//Open a thread method
        //The following methods can be executed concurrently with the thread above
        doSomething();
        try {
            futureTask.get();//Get thread return value
        } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
            }
        }
    private static void doSomething() {
        // TODO Auto-generated method stub
    }
}

  1. Differences between Service and Thread threads

In fact, there is not much relationship between them, but many friends often confuse the two! Thread is the thread, the smallest unit of program execution, and the basic unit of CPU allocation! Service is a component provided by Android that allows you to stay in the background for a long time. The most common usage is polling! Or want to do something in the background, such as downloading updates in the background! Remember not to confuse these two concepts!

IV Service Lifecycle

Life cycle function analysis:
1) This method will be called once in the whole life cycle: onCreate()!
2) onDestory(): this method will be called back when the Service is closed. This method will only call back once!
3) onStartCommand(intent,flag,startId): the previous version was onStart(intent,startId). When the client calls the startService(Intent) method, it will call back. You can call the StartService method multiple times, but will not create a new Service object. Instead, you will continue to reuse the Service object generated earlier, but will continue to call back the onStartCommand() method!
IBinder onOnbind(intent): this method is a method that all services must implement. This method will return an IBinder object through which app communicates with Service components!
4) onUnbind(intent): this method will be called back when all clients bound to this Service are disconnected!

V Service startup mode

1) StartService() start Service
2) BindService() start Service
PS: another way is to bind the Service after starting the Service

  • StartService start Service

① The first startup will create a Service instance and call onCreate() and onStartCommand() methods successively. At this time, the Service will enter the running state. If you call StartService again to start the Service, no new Service object will be created. The system will directly reuse the previously created Service object and call its onStartCommand() method!
② However, such a Service has no necessary connection with its caller, that is, when the caller ends its life cycle, but as long as it does not call stopService, the Service will continue to run!
③ No matter how many times the Service is started, you only need to call StopService once to stop the Service

  • BindService starts service

(1) when bindService is first used to bind a Service, the system instantiates a Service instance and calls its onCreate() and onBind() method. Then the caller can interact with IBinder and Service. After that, if the bindService binding Service is used again, the system will not create a new Sevice instance, and will no longer invoke the onBind() method. Only the ibinder object will be directly passed to other clients added later!
② If we unbind the service, we just need to call unbindService(), and then the onUnbind and onDestory methods will be called! This is the case of a client. If multiple clients bind the same service, the situation is as follows. When a client completes the interaction with the service, it calls the unbindService() method to unbind. When all clients are unbound from the service, the system will destroy the service. (unless the service is also opened by the startService() method)
(start)
③ In addition, different from the above situation, the Service in bindService mode is associated with the caller. It can be understood as "grasshopper on a rope". If you want to die together, after bindService, once the caller is destroyed, the Service will be terminated immediately!
Resolution of the bindservice of the Context called when calling Service through bindservice
bindService(Intent Service,ServiceConnection conn,int flags)
Service: specify the service to be started through this intent
conn:ServiceConnection object. The user listens to the connection between the visitor and the Service. After the connection is successful, call back the onServiceConnected(ComponentName,IBinder) method in the object; If the host of the Service terminates due to abnormal termination or other reasons, resulting in the disconnection between the Service and the visitor, call the onServiceDisconnected(CompanentName) method. Actively disconnecting through the unBindService() method will not call the above method!
flags: Specifies whether to automatically create a Service when Binding (if the Service has not been created yet). The parameters can be 0 (not automatically created) and bind_ AUTO_ Create (automatic creation)

  • StartService bindService binding after starting Service

If Service has been activated by a client through StartService(), then the other client will then call bindService() to bind to the Service and then call unbindService() to unbind. Finally, when calling bindService() to bind to Service, the life cycle method triggered at this time is as follows:
onCreate( )->onStartCommand( )->onBind( )->onUnbind( )->onRebind( )
PS: premise: onUnbind() method returns true!!! Some readers may have doubts here. After calling unbindService, shouldn't the Service call onDistory() method! In fact, this is because this Service is started by our StartService, so you call onUnbind() method to unbind, and the Service will not terminate!
Conclusion: if we use bindService to bind a started Service, pay attention to the started Service!!! The system only passes the internal IBinder object of the Service to the Activity, and does not bind the Service life cycle to the Activity. Therefore, when calling the unBindService() method to unbind, the Service will not be destroyed!

Topics: Java Android html