Lesson 92. Service. a simple example

Lesson 92. Service. a simple example


In this lesson:

– create, start and stop simple service

First, you need to decide what to call in Russian Service. Conventional translation is a service. The most popular example is Windows services. But for Android, I’m more familiar with the word service. I will use it in my lessons to refer to Service.

And one more point needs to be clarified at once. Service is listed in the manifest next to Activity, and it turns out that the application (Application) includes both Activity and service. I suggest to simplify the presentation of the material under the word appendix to understand all the same Activity, which can be run and seen on the screen. That is what we used to call an application. And consider the service a separate thing from the app. And if I need to mark the application as a container for Activity and service, I will use the word Application.

That is, the application is a set of Activity, service – Service. Application + Service = Application. Somehow.

So service is some kind of task that runs in the background and doesn’t use UI. You can start and stop the service from applications and other services. You can also connect to an already running service and interact with it.

An example is the mail program algorithm. It consists of a program and a service. The service runs in the background and periodically checks for new mail, downloads it and displays messages. And when you launch the application, it shows you these downloaded emails. The application can also connect to the service and change it, for example, a mail check period, or close the service altogether, if you do not need constant mail checking.

That is, the service is required to keep your task running even when the application is closed. In the coming lessons, we will understand what methods of interaction between the application and the service. In the same lesson, we will create the simplest service that will output anything to the log. And the application will start and stop the service.

Let’s create a project:

Project name: P0921_ServiceSimple
Build Target: Android 2.3.3
Application name: ServiceSimple
Package name: en.startandroid.develop.p0921servicesimple
Create Activity: MainActivity

Add to strings.xml rows:

Start service
Stop service	

screen main.xml:



	
	
	
	

Two buttons – to start and stop the service. And ProgressBar.

Near MainActivity create a class MyService, next android.app.Service

contents MyService.java:

package ru.startandroid.develop.p0921servicesimple;

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

public class MyService extends Service {
  
  final String LOG_TAG = "myLogs";

  public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "onCreate");
  }
  
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(LOG_TAG, "onStartCommand");
    someTask();
    return super.onStartCommand(intent, flags, startId);
  }

  public void onDestroy() {
    super.onDestroy();
    Log.d(LOG_TAG, "onDestroy");
  }

  public IBinder onBind(Intent intent) {
    Log.d(LOG_TAG, "onBind");
    return null;
  }
  
  void someTask() {
  }
}

The service has the same methods as Activity onCreate and onDestroy – which work when creating and destroying a service.

OnStartCommand method – Fires when the service is started by the startService method. In it, we run our method someTaskWhich is still empty. IN onStartCommand the input and output are parameters, we are not using them yet.

method onBind we are not curious yet. But we have to implement it, we return null.

someTask – here we will code the work for the service

The service, as well as the new ones created by Activity, must be registered in the manifest. This is done quite similarly. press Add, you choose Service. And in the field Name you choose MyService.

MainActivity.java:

package ru.startandroid.develop.p0921servicesimple;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {
  
  final String LOG_TAG = "myLogs";
  
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    }
    
    public void onClickStart(View v) {
      startService(new Intent(this, MyService.class));
    }
    
    public void onClickStop(View v) {
      stopService(new Intent(this, MyService.class));
    }
}

Here we have two methods that work when you press the buttons Start service and Stop service. In them, we respectively start or stop the service methods startService and stopService. We send Intent to the input, which indicates the service. This is very similar to how we call Activity using the startActivity method.

Let’s save everything and launch the application.

we press Start service and look at the log:

onCreate
onStartCommand

the method was executed onCreate – the service was created, and onStartCommand – the service executes the contents of the onStartCommand method.

If we press again now Start service:

onStartCommand

Service already created, onCreate not called, only method is executed onStartCommand.

press Stop service

onDestroy

The service was destroyed.

Make sure that the service is independent of the program. press Start service.

onCreate
onStartCommand

Service started. Close the application with the Back button. In the logs of silence, onDestroy the service is not fulfilled, the service continues to live. He doesn’t care if the application is running, running it or not.

Long press the Home key to display a list of the latest applications

reopen our application and click Stop service. In the logs:

onDestroy

Service destroyed.

Now let’s try to do something meaningful in onStartCommand. rewrite the method someTask in MyService.java:

  void someTask() {
    for (int i = 1; i<=5; i++) {
      Log.d(LOG_TAG, "i = " + i);
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

We will with an interval of 1 second output logs from the service.

We will save everything, run it and click Start service:

ProgressBar stopped, the screen became unavailable. And the logs are:

onCreate
onStartCommand
i = 1
i = 2
i = 3
i = 4
i = 5

Conclusion - the service runs in the main stream and locks the screen.

Take the paused loop into a separate stream. And to avoid running twice, let's learn at the same time what the stopSelf method does.

rewrite the method someTask:

  void someTask() {
    new Thread(new Runnable() {
      public void run() {
        for (int i = 1; i<=5; i++) {
          Log.d(LOG_TAG, "i = " + i);
          try {
            TimeUnit.SECONDS.sleep(1);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        stopSelf();
      }
    }).start();
  }

We extracted the code into a separate thread and added a method call stopSelf - this method is similar to the method stopService, It stops the service in which it was called.

We save, run and click everything Start service. ProgressBar rotates, screen not blocked, logs go:

onCreate
onStartCommand
i = 1
i = 2
i = 3
i = 4
i = 5
onDestroy

The service was created, completed the work and stopped by the method itself stopSelf.

In the next lesson:

- transfer the data to the service
- we consider methods of stop service stopSelf and stopSelfResult




Discuss in the forum [98 replies]

Leave a Comment