Writing in the front

  • Record the use of learning services
  • IDE: Android-Studio SDK version: API30

1. Service basics

1.1 Concepts related to threads:

Let’s look at threads before we look at services.

  • Program: A set of instructions (a set of static code) written in a language to accomplish a specific task.
  • Process: A running program, an independent unit of system scheduling and resource allocation. The operating system allocates memory space to each process. The program in turn dynamic execution, through the code load, execute, execute the complete process.
  • Thread: a unit of execution smaller than a process. Each process may have multiple threads that need to be placed in a process to execute. Threads are managed by the program and processes are scheduled by the system.
  • Multi-threaded understanding: parallel execution of multiple instructions, the CPU time slice allocated to each thread according to the scheduling algorithm, is actually timeshare execution, but this switch time is very short, users feel “at the same time”.

1.2 Thread lifecycle

1.3 Three ways to create a thread

  1. Thread class inheritance
  2. Implement the Runnable interface
  3. Implement Callabl interface

1.4 Differences between Services and Threads

They don’t have much to do with each other, but a lot of people confuse the two. A Thread is the smallest unit of program execution, and the basic unit of CPU allocation. A Service is a component that Android provides that allows you to stay in the background for long periods of time. The most common use is polling. Or you want to do something in the background, like download updates in the background. Remember not to confuse the two concepts.

1.5 Service life cycle diagram

1.6 Service Life cycle Analysis

  • StartService() Starts the Service.
  • BindService() starts the Service.
  • Another option is to start a Service and bind it

1.7 Detailed explanation of relevant methods

  • OnCreate () : Calls back to the method immediately after the Service is created for the first time. The method is called only once in its lifetime.
  • OnDestory () : this method is called back when the Service is closed, but only once.
  • OnStartCommand (intent, flag, startId) : In earlier versions, onStart(Intent,startId) is called when the client calls startService(Intent). The startService can be called multiple times, but no new Service object is created. Instead, we continue to reuse the previously generated Service object, but continue to call back the onStartCommand() method.
  • IBinder onOnbind(Intent) : This method must be implemented by any Service. The method returns an IBinder object through which the APP communicates with the Service component.
  • OnUnbind (Intent) : this method is called back when all clients bound to the Service are disconnected.

2. Verify the Service life cycle

2.1 To define a Service, rewrite the related methods, and print the verification on logcat:

Write the layout file and add two Button components with Id set to startButton and stopButton respectively

activity_main.xml


      
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="100dp">

        <Button
            android:id="@+id/startButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:text="Start" />

        <Button
            android:id="@+id/stopButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="122dp"
            android:text="Stop" />
    </TableRow>
    
</RelativeLayout>
Copy the code

Preview the style Create a package name in the SRC /main/ Java/package name directoryTestService1Class, the code is as follows:

package com.czie.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class TestService1 extends Service {
    @Nullable
    @Override
    // The method that must be implemented
    public IBinder onBind(Intent intent) {
        Log.i("CCC"."OnBind method called!");
        return null;
    }

    // called when the Service is created
    @Override
    public void onCreate(a) {
        Log.i("CCC"."OnCreate method called!");
        super.onCreate();
    }

    //Service is called when it is started
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("CCC"."OnStartCommand is called!");
        return super.onStartCommand(intent, flags, startId);
    }

    // Callback before Service is closed
    @Override
    public void onDestroy(a) {
        Log.i("CCC"."OnDestroy is called!");
        super.onDestroy(); }}Copy the code

After compiling, open the androidmanifest.xml file in the project for configuration. In the < activity… > / Activity > node add the following code:

<service android:name=".TestService1">
      <intent-filter>
    <action android:name="com.czie.service.testservice1" />
      </intent-filter>
 </service>
Copy the code

Write code in MainActivity:

package com.czie.service;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private Button start, stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = (Button) findViewById(R.id.startButton);
        stop = (Button) findViewById(R.id.stopButton);

        // Create the Intent that starts the Service, along with the Intent property
        final Intent intent = new Intent(this,TestService1.class);
        intent.setAction("com.czie.service.testservice1");
        // Set click events for two buttons, starting and stopping service respectively
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { startService(intent); }}); stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { stopService(intent); }}); }}Copy the code

Run the project and click the button to view it simultaneouslyLogThe output

2.2 Usage of IntentService

In the project of SRC/main/Java/com. Czie. Under the service to create a class called TestService3

TestService3

package com.czie.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class TestService3 extends IntentService {

    // The parent class constructor must be implemented
    public TestService3(a) {
        super("TestService3");
        // TODO Auto-generated constructor stub
    }

    // Core methods that must be overridden
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        // TODO: 2021/6/21
        // The Intent is sent from an Activity, carrying identification parameters, and performing different tasks based on the parameters
        String action = intent.getExtras().getString("param");
        if (action.equals("s1")) Log.i("ccc"."Start service1");
        else if (action.equals("s2")) Log.i("ccc"."Start service2." ");
        else if (action.equals("s3")) Log.i("ccc"."Start service3");

        // The service hibernates for 2 seconds
        try {
            Thread.sleep(2000);
        } catch(Exception e) { e.printStackTrace(); }}// Override other methods to see the order in which methods are called
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("ccc"."The onBind method is called!");
        return super.onBind(intent);
    }

    @Override
    public void setIntentRedelivery(boolean enabled) {
        Log.i("ccc"."SetIntentRedelivery has been called!");
        super.setIntentRedelivery(enabled);
    }

    @Override
    public void onDestroy(a) {
        Log.i("ccc"."OnDestroy is called!");
        super.onDestroy(); }}Copy the code

After compiling, open the androidmanifest.xml file in the project for configuration. In the < activity… > / Activity > node add the following code:

<service android:name=".TestService3">
            <intent-filter>
                <action android:name="com.czie.service.testservice3" />
            </intent-filter>
        </service>
Copy the code

Add code to MainActivity

package com.czie.service;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private Button start, stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = (Button) findViewById(R.id.startButton);
        stop = (Button) findViewById(R.id.stopButton);


        Intent it1 = new Intent(this, TestService3.class);
        Bundle b1 = new Bundle();
        b1.putString("param"."s1");
        it1.putExtras(b1);

        Intent it2 = new Intent(this, TestService3.class);
        Bundle b2 = new Bundle();
        b2.putString("param"."s2");
        it2.putExtras(b2);

        Intent it3 = new Intent(this, TestService3.class);
        Bundle b3 = new Bundle();
        b3.putString("param"."s3");
        it3.putExtras(b3);


        // Then start IntentService multiple times
        startService(it1);
        startService(it2);
        startService(it3);
        
        // Create the Intent that starts the Service, along with the Intent property
        final Intent intent = new Intent(this, TestService1.class);
        intent.setAction("com.czie.service.testservice1");
        // Set click events for two buttons, starting and stopping service respectively
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { startService(intent); }}); stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { stopService(intent); }}); }}Copy the code

Run the project and view the output of the Log

IntentServiceAt each startup, a new worker thread is created, but there is always oneIntentServiceAn instance of theWrite in the last

  • Master basic knowledge of Service and use 😀
  • Continue exploring other features of Service 💪
  • If you found this article useful, please like 👍
  • If you have any questions about this article, please point to 💖 in the comments section