Android development case 2 - start and stop service in standard binding mode, and complete addition calculation

Keywords: Android xml encoding

Android development case 2 - start and stop the service in the standard binding mode, and complete the addition calculation

Preface

1. services

When the startService() method is used to start the service, the execution life cycle method is onCreate(), onStartCommand(), and then the service is in the running state until the service stops when it calls the stopSelf() method or other components call the stopService() method, and finally it is destroyed by the system. When the bindService() method is used to start the service, the execution life cycle methods are onCreate(), onBind(), and then the service is in the running state. Until the unBindService() method is called, the service is unbound and the onUnbind() method is called, and finally it is destroyed.
2.1Manifest file

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />
        <service
            android:name=".bindService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

2.2MainActivity

package com.example.a15676.myservice;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private EditText et1;
    private EditText et2;
    private TextView tv3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et1= findViewById(R.id.tv1);
        et2=findViewById(R.id.tv2);
        tv3=findViewById(R.id.tv3);
    }
    public void start(View view)
    {
        Intent intent=new Intent(this,MyService.class);
        startService(intent);

    }
    public void stop(View view)
    {
        Intent intent=new Intent(this,MyService.class);
        stopService(intent);

    }
    ///
   //Service connection
    private  class MyConn implements ServiceConnection {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("Service lost binding");
        }

        @Override

        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("Service successfully bound");
            binder = (bindService.MyBinder) service;

        }
    }

    private MyConn myConn;
    private bindService.MyBinder binder;

//binding
    public void bind(View v) {
        Intent intent = new Intent(this, bindService.class);
        myConn=new MyConn();
        bindService(intent, myConn, Context.BIND_AUTO_CREATE);
    }
//Calculation
   public void calculate(View v) {
           int a = Integer.parseInt(et1.getText().toString());
           int b = Integer.parseInt(et2.getText().toString());
           int num=binder.callMethodInService(a,b);
          tv3.setText(String.valueOf(num));
          System.out.println("The sum is:" +num);

    }
    //Untying
    public void unbind(View v) {

        unbindService(myConn);
    }

}

2.3 interface design documents

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/b2"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="276dp"
        android:layout_height="154dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <EditText
            android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="20dp" />

        <EditText
            android:id="@+id/tv2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="20dp" />

        <TextView
            android:id="@+id/tv3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="25dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="215dp"
        android:layout_height="102dp"
        android:layout_marginBottom="8dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="start"
            android:text="Standard way to start service"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            tools:layout_editor_absoluteY="55dp" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="stop"
            android:text="Out of Service"
            app:layout_constraintEnd_toEndOf="parent"
            tools:layout_editor_absoluteY="117dp" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="219dp"
        android:layout_height="166dp"
        android:layout_marginBottom="8dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.768">

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="bind"

            android:text="Binding mode to start service" />

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="calculate"
            android:text="Additive computation" />

        <Button
            android:id="@+id/button5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="unbind"
            android:text="Unbind" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

2.4 standard method

package com.example.a15676.myservice;

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

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }
    @Override
    public void onCreate() {
        System.out.println("Service created onCreate");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
      System.out.println("The service was destroyed onDestroy");
      super.onDestroy();
    }
    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        System.out.println("Service opening onStartCommand");
        return super.onStartCommand(intent,flags,startId);
    }
}

2.5 binding method

package com.example.a15676.myservice;

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

public class bindService extends Service {

    public bindService() {
    }
   private  MyBinder myBinder;
    public class MyBinder extends Binder{
        public int callMethodInService(int a,int b){
          int x;
          x=sum(a,b);
          return x;
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        myBinder=new MyBinder();
        System.out.println("Service is bound");
        return myBinder;
    }
    @Override
    public void onCreate() {
        System.out.println("Service created");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        System.out.println("Service destroyed");
        super.onDestroy();
    }
    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        System.out.println("Service is turned on");
        return super.onStartCommand(intent,flags,startId);
    }
    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("Service is unbound");
        return super.onUnbind(intent);
    }
    public int sum(int a,int b){
       return a+b;
    }


}

3 operation
(1) Click Run to see the following interface

(2) Click the "start service in standard mode" button

(3) Click the "stop service in standard mode" button

(4) Click the "bind mode to start service" button

(5) Click "add calculation" button
Input 5, 5 and click the button to find the sum of the two numbers 10

(6) Click the "unbind" button


All right, it's over

Posted by PJ droopy pants on Mon, 27 Jan 2020 08:04:04 -0800