Monday, March 28, 2016

android - How to check if a Service is running

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:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#d2dab3"
    >
    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"
        />
    <Button
        android:id="@+id/btn_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        android:layout_toRightOf="@id/btn_start"
        android:layout_toEndOf="@id/btn_start"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
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.RelativeLayout;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private Button mButtonStart;
    private Button mButtonStop;


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

        // Get the application context
        mContext = getApplicationContext();

        // Get the activity
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButtonStart = (Button) findViewById(R.id.btn_start);
        mButtonStop = (Button) findViewById(R.id.btn_stop);

        // Initialize a new Intent instance
        final Intent intent = new Intent(mContext, RandomNumberService.class);

        // Set a click listener for start button
        mButtonStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // If the service is not running then start it
                if(!isServiceRunning(RandomNumberService.class)){
                    Toast.makeText(mContext, "Service is stopped...",Toast.LENGTH_SHORT).show();
                    // Start the service
                    startService(intent);
                }else {
                    Toast.makeText(mContext, "Service already running...",Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Set a click listener for stop button
        mButtonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // If the service is running then stop it
                if(isServiceRunning(RandomNumberService.class)){
                    Toast.makeText(mContext, "Service is running...",Toast.LENGTH_SHORT).show();
                    // Stop the service
                    stopService(intent);
                }else {
                    Toast.makeText(mContext, "Service already stopped...",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // Custom method to determine whether a service is running
    private boolean isServiceRunning(Class<?> serviceClass){
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        // Loop through the running services
        for(ActivityManager.RunningServiceInfo service : activityManager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                // If the service is running then return true
                return true;
            }
        }
        return false;
    }
}
RandomNumberService.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

import java.util.Random;

public class RandomNumberService extends Service {
    private Handler mHandler;
    private Runnable mRunnable;

    public RandomNumberService() {
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        // Send a notification that service is started
        Toast.makeText(this,"Service started",Toast.LENGTH_SHORT).show();

        // Do a periodic task
        mHandler = new Handler();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                doTask();
            }

        };
        mHandler.postDelayed(mRunnable,2000);

        return START_STICKY;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Toast.makeText(this,"Service destroyed",Toast.LENGTH_SHORT).show();
        mHandler.removeCallbacks(mRunnable);
    }

    // Custom method to do a task
    public void doTask(){
        Random rand = new Random();
        int number = rand.nextInt(100);
        Toast.makeText(this,"Random Number : " + number,Toast.LENGTH_SHORT).show();
        mHandler.postDelayed(mRunnable,2000);
    }
}
AndroidManifest.xml

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <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"
            android:label="@string/title_activity_main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

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

</manifest>