Start Service Using Alarm Manager in Android Studio

Services

Services run in the background without direct intervention by the user. Applications can use the predefined services that are provided by Android by giving the right permission in the manifest file. The user can use predefined services by extending a specific manager class and access to them by the getSysytemService( ) method. The user can also create its own services. The service is not a separate process and it is not a thread.

How to create your own service

To create our own services the user must first declare it in the Android Menifest.Xml file and the class must extend the service class. The following code will show you how to declare and implement services.

Manifest file

<service
 
android:name="MyService" 
 android:icon
="@drawable/ic_launcher"
 android:label="@string/service_name"/>

Class File

public class CreateService extends Service {

  @Override

   public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_NOT_STICKY;
 } 
   @Override

    public IBinder onBind(Intent intent) {    

        return null;

    }

}

Types of Services

Local services

When a component of an application starts and it does not have any other component running then the Android system creates a new Linux process for the application with a single thread of execution. By default all components of an application run in the same process. If a component starts and a process already exists for the other components then the component will start in that process of the application for the same thread of execution. By default Services run in the same process as the application in its own thread. Services that run in a process of an application are known as local services.  

How to declare services that run in a separate process

We write the manifests file like this:

<service 
android:name="CreateService"
android:process=":myprocess"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
</
service>

The colon prefix before the name tells Android that the service is private and will run in a separate process. If we do not use the colon then the service will be declared as global and can be used by another application. When the service runs in its own process then it does not block the application on performing a long-running task in its main thread. But as the services run in its own process you need to use some InterProcess Communication (IPC) to communicate with your service from other parts .Even if the service runs in its own process you need to use asynchronous processing to perform network access because Android does not allow network access.

Intent Services

To implement an Intent Service your class must extend the IntentService class. The intent service thereby performs some specific task in the background and when it completes its task then the instance of the Intent Service automatically terminates. An example of an Intent Service is when you download a resource from the internet. The Intent Service class provides the onHandler() method that will be called asynchronously by the Android System.

Service Lifecycle


onStartCommand()

When another component like an activity requests a service to start by calling the startService( ) method the system calls the onStartCommand method to the start service. If you use this service then it is your responsibility to stop this Service by calling the stopService( ) method. If the service is created by calling the satrtService( ) method from the system then it remains running until it will not call stopSelf( ) or the component stops it by calling the stopService() method.

OnBind( )

When the component wants to bind the services by calling the bindServices( ) method then the system calls the onBind() method. In your implementation of this method you must provide an interface that clients need to communicate with the service, by returning IBinder.
If you don't want to bind then you must return null. When the service is created by calling the bindService method from the component then the service remains running untiil the component is bound with it otherwise it will be destroyed by the system on unbind.

onCreate( )

This method is called by the system when the service is first created. If the service is already running then this method will not be called.

onDestroy( )

This method is called by the system when the service is no longer needed. It will be the last call the service receives.

5..png

Before proceeding we must understand some basic concepts for implementing services.

Pending intent

In this we use a pending intent that is ed to the Alarm Manager that allows use of the permission of your application to execute a piece of code. You use the pending.getService( ) method to call the service directly when that alarm goes off.

Alarm Manager

An Alarm Manager is a class that gives you access to the system alarm services and that allows you to schedule execution of a code at a specific time, even when your application is not running.

Calendar

Calendar is an abstract class for converting between a date object and a set of integer fields.

Step 1

Create a new project:

1..jpg

Step 2

Create a layout activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:orientation="vertical"

              android:layout_width="fill_parent"

              android:layout_height="fill_parent"       >

    <TextView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text=""         />

  <Button

           android:id="@+id/startalarm"

           android:layout_width="fill_parent"

           android:layout_height="wrap_content"

           android:text="StartService"

            />

    <Button

            android:id="@+id/cancelalarm"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="CancelSrvice"

            />

</LinearLayout>


Step 3

Create a Java Class file MainActivity.

You will be ed the pending intent to the AlarmManager to use the permission of your application as in the following:


pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);

The getService() method is provided by the pending intent that allows use of the prmission to execute a piece of code.


In this this you will use the AlarmManager class to access Alarm Manager services by calling getSystemServices() method

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

In this first you will get the object of the calendar class and then call the setTimeMills( ) to set the time of a calender.

Calendar calendar = Calendar.getInstance();

calendar.setTimeInMillis(System.currentTimeMillis());

calendar.add(Calendar.SECOND, 10);

               
package com.services; 

import java.util.Calendar;

import android.app.Activity;

import android.app.AlarmManager;

import android.app.PendingIntent;

import android.content.Intent;

import android.os.Bundle;

import android.os.SystemClock;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

 

public class MainActivity extends Activity {

    private PendingIntent pendingIntent;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button buttonStart = (Button)findViewById(R.id.startalarm);

        Button buttonCancel = (Button)findViewById(R.id.cancelalarm);

        buttonStart.setOnClickListener(new Button.OnClickListener(){

           @Override

           public void onClick(View arg0) {

                Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);

                pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);

                AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

                Calendar calendar = Calendar.getInstance();

                calendar.setTimeInMillis(System.currentTimeMillis());

                calendar.add(Calendar.SECOND, 10);

                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

                Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();

            }});

        buttonCancel.setOnClickListener(new Button.OnClickListener(){

            @Override

           public void onClick(View arg0) {

                // TODO Auto-generated method stub

                AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

                alarmManager.cancel(pendingIntent);

                Toast.makeText(MainActivity.this, "Cancel!", Toast.LENGTH_LONG).show();

            }});

 }

}

Step 4

Create a Java class file MyServiceAlarm.

package com.services;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyAlarmService extends Service {
@Override
public void onCreate() {
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
}
@Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}

Step 5

Give permission for the service to the Android manifest.xml file.
 

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.services"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="7"

        android:targetSdkVersion="16" />

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.services.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

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

            </intent-filter>

        </activity>

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

    </application>

</manifest>


Step 6

Output

When you click on the button then a toast notification becomes StartAlarm.

2..jpg

Step 7

After a few seconds of Alarm another notification becomes MyalarmService.onstart.

3..jpg

Step 8


When you click on the "Cancel" button the service wiil be stopped and a notification will become Cancel.

4..jpg
 

Up Next
    Ebook Download
    View all
    Learn
    View all