Android Lesson 10 part 2: how to check if a service is running


We create an simple example to learn how to check if a service is running. In this example, we learn how to use Handler and Runnable in a service too. (You can read this tutorials for more information: Android Lesson 5: android.os.Handler)

Step 1: create new Android project

Step 2: create new class DemoService

package com.tutorialspots.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.os.Handler;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by Tutorialspots on 1/8/2016.
 */
public class DemoService extends Service {
    public static Boolean running = false;
    private long step = 5000;
    private String currentDateandTime;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            currentDateandTime = sdf.format(new Date());
            Log.i("DemoService", currentDateandTime);
            handler.postDelayed(this, step);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("DemoService", "Service onBind");
        return null;
    }

    @Override
    public void onCreate() {
        Log.i("DemoService", "Service onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("DemoService", "Service onStartCommand");

        running = true;
        handler.postDelayed(runnable, step);

        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(runnable);
        running = false;
        Log.i("DemoService", "Service onDestroy");
    }
}

Step 3: create layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorialspots.service.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TUTORIALSPOTS.COM"
        android:textColor="#FF0000"
        android:textSize="30dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start service"
        android:id="@+id/startbtn"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="62dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop service"
        android:id="@+id/stopbtn"
        android:layout_below="@+id/startbtn"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Step 4: file MainActivity.java

package com.tutorialspots.service;

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

public class MainActivity extends AppCompatActivity {
    Button startbtn, stopbtn;

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

        // get buttons
        startbtn = (Button) findViewById(R.id.startbtn);
        stopbtn = (Button) findViewById(R.id.stopbtn);

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!DemoService.running){
                    startService(new Intent(MainActivity.this, DemoService.class));
                    Toast.makeText(getApplicationContext(), "Demo service has been started.", Toast.LENGTH_LONG).show();
                }
                else
                    Toast.makeText(getApplicationContext(), "Demo service is running.", Toast.LENGTH_LONG).show();
            }
        });

        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(DemoService.running){
                    stopService(new Intent(MainActivity.this, DemoService.class));
                    Toast.makeText(getApplicationContext(), "Demo service has been stopped.", Toast.LENGTH_LONG).show();
                }
                else
                    Toast.makeText(getApplicationContext(), "Demo service don't run yet.", Toast.LENGTH_LONG).show();
            }
        });
    }
}

Step 5: file AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".DemoService"
            android:exported="false"/>
    </application>

</manifest>

Step 6: Run for test

As soon as we click button start service, we see:

01-08 04:49:35.344 20564-20564/com.tutorialspots.service I/DemoService: Service onCreate
01-08 04:49:35.344 20564-20564/com.tutorialspots.service I/DemoService: Service onStartCommand
01-08 04:49:40.346 20564-20564/com.tutorialspots.service I/DemoService: 2016-01-08 04:49:40
01-08 04:49:45.351 20564-20564/com.tutorialspots.service I/DemoService: 2016-01-08 04:49:45

After 5s, we will get more debug message.

android service handler

If we click this button again, we get the message Demo service is running.

android service check running

So, the simplest way to check if a service is running is use the static variable running.

Leave a Reply