Android experiment: binding service experiment

Purpose

Fully understand the role of Service and the difference between it and Activity, master the life cycle and corresponding functions of Service, and understand the nature of the main thread of Service; master the design principles of the interface refresh of the main thread, and master the way to start the service. and its working principle;
In this experiment, master the principles and differences between startup and bound services, and understand their performance differences

Experiment content

  1. Implement an addition function add(int x, int y) in service
  2. And implement the call to the service method add in the Activity interface to implement addition calculation.
  3. There are two text boxes on the activity interface to enter numbers, the third text box displays the calculation results, and a button triggers the calculation.

Experimental requirements

1. Configure the operating environment of the service to ensure the correct use of the service
2. Be familiar with the method of binding the service and the operating steps of its use
3 , Fully understand the working principle and life cycle of service

Project structure

Insert image description here

Code

mainActivity

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class mainActivity extends Activity {
    
    

    private EditText etNum1, etNum2;
    private TextView tvResult;
    private Button btnCalculate;
    private AdditionService additionService;
    private boolean isBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etNum1 = findViewById(R.id.et_num1);
        etNum2 = findViewById(R.id.et_num2);
        tvResult = findViewById(R.id.tv_result);
        btnCalculate = findViewById(R.id.btn_calculate);

        btnCalculate.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                if (isBound) {
    
    
                    int num1 = Integer.parseInt(etNum1.getText().toString());
                    int num2 = Integer.parseInt(etNum2.getText().toString());
                    int result = additionService.add(num1, num2);
                    tvResult.setText(String.valueOf(result));
                }
            }
        });
    }

    @Override
    protected void onStart() {
    
    
        super.onStart();
        Intent intent = new Intent(this, AdditionService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
    
    
        super.onStop();
        if (isBound) {
    
    
            unbindService(serviceConnection);
            isBound = false;
        }
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
    
    
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
    
    
            AdditionService.LocalBinder binder = (AdditionService.LocalBinder) service;
            additionService = binder.getService();
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
    
    
            isBound = false;
        }
    };
}

AdditionService

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class AdditionService extends Service {
    
    
    private final IBinder binder=new LocalBinder();
    public class LocalBinder extends Binder{
    
    
        AdditionService getService(){
    
    
            return  AdditionService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent){
    
    
        return binder;
    }
    public int add(int x,int y){
    
    
        return x+y;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/et_num1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:hint="请输入第一个数字"
        android:inputType="number" />


    <EditText
        android:id="@+id/et_num2"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:hint="请输入第二个数字"
        android:inputType="number" />

    <Button
        android:id="@+id/btn_calculate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="计算" />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="结果是"
        android:textSize="24sp" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Exp4"
        tools:targetApi="31">
        <activity
            android:name=".mainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.Exp4">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.example.exp4.AdditionService" />
    </application>

</manifest>

Code explanation

The code is divided into three parts:

mainActivity.java: This is the main activity class, responsible for creating the user interface and binding with services. It contains the following:

Some private variables used to store two input boxes (etNum1 and etNum2), a text view that displays the results (tvResult), a calculation button (btnCalculate) and a reference to AdditionService (additionService).
A Boolean variable (isBound) used to mark whether it is bound to the service.
An onCreate method used to initialize interface elements and set click listeners for calculation buttons. When the user clicks the button, if it has been bound to the service, it gets two numbers from the input box, calls the add method of the service, and displays the results in the text view.
An onStart method, used to create an intent (intent) when the activity starts and use it to bind the service. When binding a service, you need to pass in a service connection object (serviceConnection) to monitor the connection and disconnection status of the service.
An onStop method used to unbind the service when the activity stops and set isBound to false.
A serviceConnection object, used to implement the two methods of the ServiceConnection interface: onServiceConnected and onServiceDisconnected. When the service is connected, the IBinder object of the service is obtained, converted to a LocalBinder object, and then the reference of the service is obtained through it, and isBound is set to true. When the service is disconnected, isBound is set to false.
AdditionService.java: This is a service class responsible for providing the function of adding two numbers. It contains the following:

An IBinder object (binder) used to return activities to the binding service.
An internal class (LocalBinder), inherited from the Binder class, is used to provide a getService method and return a reference to the service itself.
An onBind method used to return the binder object. This method will be called when the activity binds the service.
An add method that receives two integer parameters (x and y) and returns their sum.

activity_main.xml: This is a layout file that defines the appearance of the user interface. It contains the following:

A linear layout (LinearLayout) used to arrange all subviews vertically. Its width and height fill the parent view, and its padding is 16dp.
Two edit boxes (EditText) are used to allow users to enter two numbers. Their widths fill the parent view and their heights are both 48dp. Their prompt texts are "Please enter the number. "A number" and "Please enter a second number", their input types are both numbers.
A button (Button) is used to trigger calculation operations. Its width is the wrapped content, its height is also the wrapped content, its horizontal center is, and its text is "calculate".
A text view (TextView) used to display calculation results. Its width is the wrapping content, and its height is also the wrapping content. Its horizontal centering is, and its initial text is "The result is". It The font size is 24sp.

Results display

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/m0_72471315/article/details/134765131