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
  1. <service  
  2.  android:name="MyService"   
  3.  android:icon="@drawable/ic_launcher"  
  4.  android:label="@string/service_name"/> 
Class File
  1. public class CreateService extends Service {  
  2.   @Override  
  3.    public int onStartCommand(Intent intent, int flags, int startId) {  
  4.         return Service.START_NOT_STICKY;  
  5.  }   
  6.    @Override  
  7.     public IBinder onBind(Intent intent) {      
  8.         return null;  
  9.     }  

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:
  1. <service   
  2. android:name="CreateService"  
  3. android:process=":myprocess"  
  4. android:icon="@drawable/ic_launcher"  
  5. android:label="@string/app_name">  
  6. </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 until the component is bound with it otherwise it will be destroyed by the system on unbinding.
 
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 the 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 the 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:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:orientation="vertical"  
  4.               android:layout_width="fill_parent"  
  5.               android:layout_height="fill_parent"       >  
  6.     <TextView  
  7.             android:layout_width="fill_parent"  
  8.             android:layout_height="wrap_content"  
  9.             android:text=""         />  
  10.   <Button  
  11.            android:id="@+id/startalarm"  
  12.            android:layout_width="fill_parent"  
  13.            android:layout_height="wrap_content"  
  14.            android:text="StartService"  
  15.             />  
  16.     <Button  
  17.             android:id="@+id/cancelalarm"  
  18.             android:layout_width="fill_parent"  
  19.             android:layout_height="wrap_content"  
  20.             android:text="CancelSrvice"  
  21.             />  
  22. </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:
  1. pendingIntent = PendingIntent.getService(MainActivity.this0, myIntent, 0);
The getService() method is provided by the pending intent that allows the use of the permission to execute a piece of code.
 
In this you will use the AlarmManager class to access Alarm Manager services by calling getSystemServices() method
  1. 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 calendar.
  1. Calendar calendar = Calendar.getInstance();    
  2. calendar.setTimeInMillis(System.currentTimeMillis());    
  3. calendar.add(Calendar.SECOND, 10);   
  1. package com.services;     
  2. import java.util.Calendar;    
  3. import android.app.Activity;    
  4. import android.app.AlarmManager;    
  5. import android.app.PendingIntent;    
  6. import android.content.Intent;    
  7. import android.os.Bundle;    
  8. import android.os.SystemClock;    
  9. import android.view.View;    
  10. import android.widget.Button;    
  11. import android.widget.Toast;    
  12.      
  13. public class MainActivity extends Activity {    
  14.     private PendingIntent pendingIntent;    
  15.     @Override    
  16.     public void onCreate(Bundle savedInstanceState) {    
  17.         super.onCreate(savedInstanceState);    
  18.         setContentView(R.layout.activity_main);    
  19.         Button buttonStart = (Button)findViewById(R.id.startalarm);    
  20.         Button buttonCancel = (Button)findViewById(R.id.cancelalarm);    
  21.         buttonStart.setOnClickListener(new Button.OnClickListener(){    
  22.            @Override    
  23.            public void onClick(View arg0) {    
  24.                 Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);    
  25.                 pendingIntent = PendingIntent.getService(MainActivity.this0, myIntent, 0);    
  26.                 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);    
  27.                 Calendar calendar = Calendar.getInstance();    
  28.                 calendar.setTimeInMillis(System.currentTimeMillis());    
  29.                 calendar.add(Calendar.SECOND, 10);    
  30.                 alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);    
  31.                 Toast.makeText(MainActivity.this"Start Alarm", Toast.LENGTH_LONG).show();    
  32.             }});    
  33.         buttonCancel.setOnClickListener(new Button.OnClickListener(){    
  34.             @Override    
  35.            public void onClick(View arg0) {    
  36.                 // TODO Auto-generated method stub    
  37.                 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);    
  38.                 alarmManager.cancel(pendingIntent);    
  39.                 Toast.makeText(MainActivity.this"Cancel!", Toast.LENGTH_LONG).show();    
  40.             }});    
  41.  }    
  42. }   
Step 4
 
Create a Java class file MyServiceAlarm.
  1. package com.services;  
  2. import android.app.Activity;  
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.IBinder;  
  6. import android.widget.Toast;  
  7. public class MyAlarmService extends Service {  
  8.  @Override  
  9.  public void onCreate() {  
  10.   Toast.makeText(this"MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();  
  11.  }  
  12.  @Override  
  13.  public IBinder onBind(Intent intent) {  
  14.   Toast.makeText(this"MyAlarmService.onBind()", Toast.LENGTH_LONG).show();  
  15.   return null;  
  16.  }  
  17.  @Override  
  18.  public void onDestroy() {  
  19.   super.onDestroy();  
  20.   Toast.makeText(this"MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();  
  21.  }  
  22.  @Override  
  23.  public void onStart(Intent intent, int startId) {  
  24.   super.onStart(intent, startId);  
  25.   Toast.makeText(this"MyAlarmService.onStart()", Toast.LENGTH_LONG).show();  
  26.  }  
  27.  @Override  
  28.  public boolean onUnbind(Intent intent) {  
  29.   Toast.makeText(this"MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();  
  30.   return super.onUnbind(intent);  
  31.  }  
Step 5
 
Give permission for the service to the Android manifest.xml file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.services"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.    
  7.     <uses-sdk  
  8.         android:minSdkVersion="7"  
  9.         android:targetSdkVersion="16" />  
  10.    
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name="com.services.MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.    
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.         </activity>  
  25.  <service android:name=".MyAlarmService" />  
  26.     </application>  
  27. </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 will be stopped and a notification will become Cancel.
 
4..jpg


Similar Articles