Android Development Sample

Hello! Today I want to show you how to create, start and stop simple service in Android OS.

Thus, the service is a certain task that runs in the background and does not use UI. The service can be started and stopped from applications and other services. Also, you can connect to the running service and interact with it.

As an example, let’s consider the algorithm of a mailer. It consists of applications and services. The service works in the background and periodically checks for new mail, downloads it and displays a notification. When you launch the app, it shows you those emails downloaded by the service. Also, the application can connect to the service, and change, for example, the frequency of email scan or close the service, if the constant checking is no longer needed.

So the service is needed to make your task working, even when the app is closed. In this example, you will understand what methods of cooperation between the application and service exist. We will create a simple service that will print anything to the log. And the app will start and stop the service.

Create a project:

Project name: P0921_ServiceSimple
Build Target: Android 2.3.3
Application name: ServiceSimple
Package name: ru.startandroid.develop.p0921servicesimple
Create Activity: MainActivity
Add such text to strings.xml:

<string name="start">Start service</string>
<string name="stop">Stop service</string>

And such text to main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
	<Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClickStart" android:text="@string/start">
	</Button>
	<Button android:id="@+id/btnStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClickStop" android:text="@string/stop">
	</Button>
	<ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminate="true">
	</ProgressBar>
</LinearLayout>

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

Create MyService class inherited from the android.app.Service near the MainActivity:

android-development-sample-1

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 onCreate and onDestroy methods that run in case of starting and stopping the service.

OnStartCommand method triggers when the service starts with startService method. There we run our method someTask, which is empty for now. OnStartCommand has inbound and outbound parameters which are not used for now.

We will code the work of the service in someTask method.

We should note the service in the manifest:

android-development-sample-2

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);

		}
		
		 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 trigger on the Start service and Stop service buttons. Respectively in them, we start and stop the service using startService and stopService methods. Inbound we pass Intent, that points to the service.

So let’s save everything and run the application:

android-development-sample-3

Push Start service and check the log:

onStartCommand

The service was created, onCreate and onStartCommand methods triggered.

Push Start service one more time:

onStartCommand 

The service is already created so  onCreate didn’t trigger, but onStartCommand did.

Push Stop service:

Service was destroyed.

Let’s make sure that service doesn’t depend on the application. Push Start service

onCreate
onStartCommand

Service have started. Close the application pushing the Back button. Logs are empty, onDestroy method didn’t trigger, service is still working.
Long push the Home button to see the recent applications:

android-development-sample-4

Open our app again and push Stop service. In logs we see:

onDestroy

The service is destroyed.

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

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

Let’s output the notes from the service to the log each second:

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

So the service is running in the main thread.

Let’s expose the cycle with pauses to the separate thread and also run the stopSelf method. Rewrite the someTask method:

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 have exposed the code to the separate thread and added the stopSelf method which is similar to stopService method. It stops the service that called it.
Save everything, execute and push Start service. ProgressBar is spinning, screen is not blocked, logs are coming:

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

So the service was created, done its job and was stopped by the stopSelf method.

In case you missed, we posted once more sample Android application code before

We recommend viewing this Android development sample at the beginning, and during, your course of computer science so that you have an idea what your professor expects you to hand in. The sample of assignment is perfect for most students and contains material that can help you to deal with your own homework. If you have any question about your assignment, you can always get help from AssignmentShark.com. We have a team of experts that includes only professionals with long-term experience in dealing with any assignment. All assignments are done quickly and according to your requirements. Use our service to make your homework done successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *

Customer testimonials

Submit your instructions to the experts without charge.