Google Search

How To Create Background Service In Android

=> Here I explain Android Service using One Simple Example Of When Service Is Start at that time Default ringtone is Start.

   What Is Service?

                              Service is a Long time Background process.in this service used many way like play music,phone call receive etc.


Once Service is start then Application is remove in recent app list.so this app can not close because of service is start in Background .

    In this Tutorial create one xml file in this file create are two buttons Service Start And Service Stop.


 When Service Start is press then check if you running already a service then open alert dialog box to choose service is running you want to stop a service.




Service Layout 


Background Android Service


start service


already service starting

service stop

Layout xml File

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:ads="http://schemas.android.com/tools"
    android:background="#5cdf88">

    <TextView
        android:textStyle="bold"
        android:textColor="#434844"
        android:layout_marginTop="60dp"
        android:layout_centerHorizontal="true"
        android:text="Welcome To Service Example"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="#a1cc98"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_start"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="40dp"
            android:background="@drawable/bt_bg"
            android:text="Service Start"
            android:textAllCaps="false"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/white" />

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="40dp"
            android:background="@drawable/bt_bg"
            android:text=" Service  Stop"
            android:textAllCaps="false"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/white" />
    </LinearLayout>
    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_home_footer">
    </com.google.android.gms.ads.AdView>
</RelativeLayout>

Main Activity Javafile


package com.college.servicedemo;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
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;

import com.crashlytics.android.Crashlytics;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import io.fabric.sdk.android.Fabric;

public class MainActivity extends AppCompatActivity {
    Button btn_start, btn_stop;
    private AdView mAdView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fabric.with(this, new Crashlytics());
        setContentView(R.layout.activity_main);

// this Three line Code is addmob Add Code so if you dont want to include add then dont write this code....

        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
//............Admob Ad Code.


        btn_start = (Button) findViewById(R.id.btn_start);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isMyServiceRunning(MyService.class)) {
                    final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                    alert.setMessage("You Want To Stop Service ?")
                            .setTitle("Service is Running");
                    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            stopService(new Intent(MainActivity.this, MyService.class));
                        }
                    });
                    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    });
                    AlertDialog alert11 = alert.create();
                    alert11.show();
                    Toast.makeText(MainActivity.this, "FirstStop The running serivce", Toast.LENGTH_SHORT).show();
                } else {
                    startService(new Intent(MainActivity.this, MyService.class));
                }
            }
        });
        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isMyServiceRunning(MyService.class)) {
                    final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                    alert.setMessage("You Want To Stop Service ?")
                            .setTitle("Service is Running");
                    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            stopService(new Intent(MainActivity.this, MyService.class));
                        }
                    });
                    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    });
                    AlertDialog alert11 = alert.create();
                    alert11.show();
                   // Toast.makeText(MainActivity.this, "FirstStop The running serivce", Toast.LENGTH_SHORT).show();
                } else {
                   // startService(new Intent(MainActivity.this, MyService.class));
                }
            }
        });
    }

    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

My Service.Java file


package com.college.servicedemo;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.audiofx.BassBoost;
import android.media.audiofx.EnvironmentalReverb;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by admin on 01-09-2017.
 */

public class MyService extends Service {
    MediaPlayer player;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
        player.setLooping(true);
        player.start();
        Log.d("service", "Start");
        Toast.makeText(this, "StartService", Toast.LENGTH_SHORT).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.stop();
        Log.d("service", "Stop");
        Toast.makeText(this, "StopService", Toast.LENGTH_SHORT).show();
    }
}

Manifest File


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.college.servicedemo">
    <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:roundIcon="@mipmap/ic_launcher_round"
        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>
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <service android:name=".MyService" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />
        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="029834fec845a76f87f892037d98209d2d1dbff3" />
    </application>

</manifest>

btn_bg Drawable File


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:centerColor="#5e684b" android:startColor="#0f4ece" android:endColor="#243b5b"/>
    <corners
        android:radius="5dp"></corners>
</shape>