A simple case of starting and terminating Android Service and data transmission

Keywords: Android xml encoding Java

Brief introduction to life cycle method

startService()

Role: start Service service
After manually calling startService(), internal methods are automatically called: onCreate(), onStartCommand()
If a service is started multiple times by startService, onCreate() will only call once
onStartCommand() calls = startService() calls

stopService()

Role: close Service service
After manually calling stopService(), the internal method is automatically called: ondestore()
If a service is started and bound, stopService() cannot stop the service without binding.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editData"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="This is the default message"
        android:inputType="textPersonName"
        android:text="This is the default message"
        android:layout_width="match_parent" />
    <Button
        android:id="@+id/btnStartService"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="Opening service"
      />

    <Button
        android:id="@+id/btnStopService"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="Termination of service" />


</LinearLayout>

Then create a new MyService Service that inherits from the Service, and override the onCreate(), onStartCommand(), and onDestroy() methods of the parent class, as follows:

package com.example.dpl.demoservice;

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

public class MyService extends Service {
    private boolean running=false;
    private String data="This is the default message";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    //Execute onCreate() and the method after MainActivity finishes executing startService
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        data=intent.getStringExtra("data");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {  //service is called when it is first created
        super.onCreate();
        running=true;
        new Thread(){    //Execute background thread
            @Override
            public void run() {
                super.run();

                while (running){    //Loop printing
                    System.out.println(data);
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public void onDestroy() {   //Shut down service
        super.onDestroy();
        running=false;
    }
}

MainActivity.java

package com.example.dpl.demoservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editData=findViewById(R.id.editData);
        findViewById(R.id.btnStartService).setOnClickListener(this);
        findViewById(R.id.btnStopService).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.btnStartService:
                Intent intent=new Intent(this,MyService.class);
                //Transfer parameters
                intent.putExtra("data",editData.getText().toString().trim());
                startService(intent);
                break;
            case R.id.btnStopService:
                stopService(new Intent(this,MyService.class));
                break;
        }
    }
}

Operation result:

I/System.out: This is the default message 5
 I/System.out: This is the default message 5
 I/System.out: This is the default message 0
 I/System.out: This is the default message 0
 I/System.out: This is the default message 0
 I/System.out: This is the default message 0
 I/System.out: This is the default message 0

 

Posted by bg on Mon, 30 Dec 2019 20:44:51 -0800