Android Service Example With Vibration(Background task)

  • 2
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

In this android Example, we will discuss One Of the major Android Component That is used in Many Applications For Long Running task.You will Learn all the Topics related to Services in this Tutorial.We Will Start a Service and Vibrate the Device after Every 5 Second To Check our Service is Running Or not after App is Closed.

The Topics we will cover :

  1. What is Services?
  2. Types of services in Android
  3. Implementation of Services.

You can learn more about Android Components here

What is Services?

To know about what is services in android click here

Types of Services in Android

There are two types of Services in android

  1. Bounded Services
  2. Started Services (Unbounded Services)

Below is the Diagram Showing the LifeCycle of every Single Service.

Service LifeCycle with its types

 

Bounded Service:- As Seen in Image to Start this Service first we have to call onBind() method.This will bind the Service with BrodcastReceiver or Activity of the App So when will be the Activity Change the Service will destroy automatically.

Started Service:- This Service is Not Bounded With Any Element We can Start this Service from any Activity or Class or Can Stop this Anywhere.

In this Example, We Will See About Started Services (unbounded services).

 

Implementation of Services

So, guys Let’s Start

  1. Create a New Project by going to File » New Project.Fill all the details and name your activity as MainActivity.
  2. Once the project is created open your activity_main.xml file and Add Below Code.

 

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout 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:orientation="vertical"  
   tools:context="com.targetandroid.info.myservice.MainActivity">  
   
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:text="Start Service"  
     android:id="@+id/bt_startservice"/>  
   
   
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:text="Stop Service"  
     android:id="@+id/bt_stopservice"/>  
 </LinearLayout>  

You will Find a Below Output With This Code.

Output of Android Service Tutorial Service Layout

3. Now create a new Class and Named it As MyService.java extend that class with Service and Implement some abstract Methods or Add Below Code into That

 package com.targetandroid.info.myservice;  
   
 import android.app.Service;  
 import android.content.Intent;  
 import android.os.IBinder;  
 import android.os.Vibrator;  
 import android.support.annotation.Nullable;  
 import android.widget.Toast;  
   
 /**  
  * Created by Faizan on 16-11-17.  
  */  
   
 public class MyService extends Service {  
   
   //create time variable to count how much time the service in running  
   int time=0;  
     
   //this will start and stop our service  
   boolean stop=false;  
   
   public MyService() {  
   }  
   
   @Nullable  
   @Override  
   public IBinder onBind(Intent intent) {  
     return null;  
   }  
   
   
   //this method Will Start Our Service  
   @Override  
   public int onStartCommand(Intent intent, int flags, int startId) {  
   
     Toast.makeText(this, "Service Started at " + String.valueOf(time), Toast.LENGTH_SHORT).show();  
   
   
     Thread t=new Thread(){  
   
       @Override  
       public void run() {  
         while (!stop) {  
             
           try {  
             //to run the thread every second  
             sleep(1000);  
   
   
           } catch (InterruptedException e) {  
   
             e.printStackTrace();  
   
           }  
           //increase value of time by one  
           time++;  
             
           //phone will vibrate after every 5 second  
           if (time % 5 == 0) {  
   
             Vibrator v = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE);  
             v.vibrate(500);  
   
           }  
   
         }  
       }  
     };  
     t.start();  
     return START_NOT_STICKY;  
   }  
   
   //this method we call when we stop our Service  
   @Override  
   public void onDestroy() {  
     super.onDestroy();  
     stop=true;  
     Toast.makeText(this, "Service Destroyed after " + String.valueOf(time)+" Second", Toast.LENGTH_SHORT).show();  
   }  
 }  

4. Now Open Our MainActivity.class and Add Below Code

package com.targetandroid.info.myservice;  
   
 import android.content.Intent;  
 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.widget.Button;  
   
 public class MainActivity extends AppCompatActivity {  
     
   private Button bt_startservice,bt_stopservice;  
     
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     bt_startservice=(Button)findViewById(R.id.bt_startservice);  
     bt_stopservice=(Button)findViewById(R.id.bt_stopservice);  
           
       
       
     bt_startservice.setOnClickListener(new View.OnClickListener() {  
   
       @Override  
       public void onClick(View v) {  
         startservice();  
       }  
     });  
   
     bt_stopservice.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         stopservice();  
   
       }  
     });  
   
   
   }  
   
   //Start Our Service  
   private void stopservice() {  
   
     stopService(new Intent(getBaseContext(), MyService.class));  
   
   }  
   
   //Kill or Destroy our Service  
   private void startservice() {  
   
     startService(new Intent(getBaseContext(),MyService.class));  
   }  
 }  

5. Before running Your Project add this two Set of Code into AndroidManifest.xml

  • Add a Permission Above Application Tag for Vibration
 <uses-permission android:name="android.permission.VIBRATE" /> 
  • Declare the Service Class which we have named it as MyService.class inside Application tag
<service  
       android:name=".MyService"  
       android:enabled="true">  
     </service>  

 

This is My AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.targetandroid.info.myservice">  
   
   <uses-permission android:name="android.permission.VIBRATE" />  
   
   <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>  
   
     <service  
       android:name=".MyService"  
       android:enabled="true">  
     </service>  
   
   </application>  
   
 </manifest>  

6. Now Finally Run Your Project You will Find a Below Output

 

Output of Android Service Tutorial Service Started    Output of Android Service Tutorial Service Stopped

 

Subscribe to Our Newsletter So You Will get a mail When I Post a New Tutorial on My Website.

ThankYou


  • 2
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Add a Comment

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