Android Services Example

A service is a class which will run in background without any interaction with user interface. The task which should be running for a longer period of time even if the application is no longer also ,can be given in a service class.In this tutorial we will see a simple example for how to implement a service class in android. Let us start by creating new project in android studio.

1.Creating New Project

  1. Create a new project in Android Studio from File -> New Project
  2. Fill the required fields like Application name and package name and click Next
  3.  Select Basic activity and click Next, and click  Finish Button.A default activity will be created as MainActivity.java with layouts activity_main.xml and content_main.xml

2. Here is the code for your activity_main.xml

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="codes4.com.services.MainActivity">

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

3. following is the code for res/layout/content_main.xml, the layout will contain two buttons to start and stop service tasks.

content_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="codes4.com.services.MainActivity"
tools:showIn="@layout/activity_main">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical">

<Button
android:id="@+id/btn_start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/imageButton"
android:background="@color/colorPrimary"
android:textColor="@color/white"
android:text="Start Services" />

<Button
android:id="@+id/btn_Stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:textColor="@color/white"
android:layout_marginTop="10dp"
android:text="Stop Services" />

</LinearLayout>

</RelativeLayout>

4. Following is the code for java/yourpackage/MainActivity.java

MainActivity.java


import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Toolbar toolbar;

Button btn_start_service,btn_stop_service;

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

init();

}

private void init() {

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

btn_start_service = (Button) findViewById(R.id.btn_start_service);
btn_stop_service = (Button) findViewById(R.id.btn_Stop_service);

btn_stop_service.setOnClickListener(this);
btn_start_service.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {


if(v.getId() == R.id.btn_start_service){

start();

}else if(v.getId() == R.id.btn_Stop_service){

stop();

}
}


// Method to start the service
public void start() {
startService(new Intent(getBaseContext(), MyService.class));
}

// Method to stop the service
public void stop() {
stopService(new Intent(getBaseContext(), MyService.class));
}
}

5. Create a file under java/your package/ and name it as MyService.Java .The task which should be executed in backgroud can be given in this class.

MyService.java

package codes4.com.services;

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

/**
 * Created by rameesfazal on 23/7/16.
 */
public class MyService extends Service {

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

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
 // Let it continue running until it is stopped.
 Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
 return START_STICKY;
 }

 @Override
 public void onDestroy() {
 super.onDestroy();
 Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
 }

}

6. finally add the below code to your AndroidManifest.xml


<service android:name=".MyService" />

7.Here is the full code for AndroidManifest

AndroidManifest.xml


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

<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/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

<service android:name=".MyService" />

</application>

</manifest>

8.Here is the full code for color.xml

color.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="white">#FFFFFF</color>
</resources>

Output

android_services

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

One Comment

Add a Comment

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