Android Services

 

Android Services

Android services is a part that keeps running out of sight to perform long-running operations without expecting to communicate with the client and it works even if that application is annihilated. An Android Service can basically take two services

State              Description   of  Android Services

Started  –  Android services which  begun when an application component, for example, an activity, begins it by calling startService(). Once began, a service can keep running out of sight indefinitely, regardless of the possibility that the component that began it is destroyed.

 

Bound  –  Android services is bound when an application components ties to it by calling bindService(). A bound service offers a customer server interface that permits parts to associate with the service, send requests, get results, and even do as such crosswise over procedures with interprocess correspondence (IPC).

Android services has lifecycle callback techniques that you can execute to screen changes in the services state and you can perform work at the fitting stage. The following chart on the left shows the life cycle when the service is made with startService() and the picture on the right represents the life cycle when the service is made with bindService(): (picture courtest : android.com )

 

android services

To made android services, you produce a Java category that extends the Service base category or one among its existing subclasses. The Service base category defines varied callback ways and therefore the most vital square measure given below. you do not have to be compelled to implement all the callbacks ways. However, it is vital that you just perceive each and implement those who guarantee your app behaves the approach users expect.

Callback                     Description

onStartCommand()  –  The system calls this method once another part, like An activity, requests that the service is started, by calling startService(). If you implement this technique, it’s your responsibility to prevent the service once its work is finished, by calling stopSelf() or stopService() ways.

onBind()  –  The system calls this technique once another part desires to bind with the service by calling bindService() –If you implement this technique, you want to offer An interface that users use to communicate with the service, by returning an IBinder object. you want to forever implement this technique, however, if you do not wish to permit binding, then you ought to come back null.

onUnbind()  –  The system calls this technique once all users have disconnected from a selected interface published by the service.

onRebind()   –  The system calls this technique once new users have connected to the service, once it had antecedently been notified that each one had disconnected in it’s onUnbind(Intent).

onCreate()  –  This service is initial created using onStartCommand() or onBind(). This decision is needed to perform one-time set-up.

onDestroy()  –  The system calls this technique once the service isn’t any longer used and is being destroyed. Your service ought to implement this to scrub up any resources like threads, registered listeners, receivers, etc.

Skeleton service demonstrates each and every of thy cylcle methods, given below

package com.androdevevlopment;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {
   
   /** indicates how to behave if the service is killed */
   int mStartMode;
   
   /** interface for clients that bind */
   IBinder mBinder;     
   
   /** indicates whether onRebind should be used */
   boolean mAllowRebind;

   /** Called when the service is being created. */
   @Override
   public void onCreate() {
     
   }

   /** The service is starting, due to a call to startService() */
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      return mStartMode;
   }

   /** A client is binding to the service with bindService() */
   @Override
   public IBinder onBind(Intent intent) {
      return mBinder;
   }

   /** Called when all clients have unbound with unbindService() */
   @Override
   public boolean onUnbind(Intent intent) {
      return mAllowRebind;
   }

   /** Called when a client is binding to the service with bindService()*/
   @Override
   public void onRebind(Intent intent) {

   }

   /** Called when The service is no longer used and is being destroyed */
   @Override
   public void onDestroy() {

   }

 

This simple example will find a way to demonstrate to make your own particular Android Service. Just follow these steps to change the Android application we made in Hello World Example tutorial:

Steps              Description

1       –       You will have to make use of Android StudioIDE to make an Android app and name it as My Application under a bundle com.example.My Application as clarified in the Hello World Example tutorial.

      –       Modify main activity file  MainActivity.java to include startService() and stopService() techniques/methods.

3      –        Create another java file MyService.java under the bundle com.example.My Application. This file will have usage of Android service related techniques.

4       –       Define your service in AndroidManifest.xml file utilizing <service…/> tag. An application can have one or more services with no confinements.

5        –      Modify the default substance of res/design/activity_main.xml file to incorporate two buttons in straight layout.

6         –     No need to change any constants in res/values/strings.xml file. Android studio deal with string values

7          –    Run the application to dispatch Android emulator and check the aftereffect of the progressions done in the application.

Taking after is the content of the changed main activity file src/com.example.My Application/MainActivity.java. This file can incorporate each of the fundamental life cycle strategies. We have included startService() and stopService() strategies to begin and stop the service.

package com.example.My Application;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.activity_main, menu);
      return true;
   }

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

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

 

The content of src/com.example.MyApplication/MyService.java is given below. This file can have implementation of one or more methods associated with Service based on requirements. For now we are going to implement only two methods onStartCommand() and onDestroy() –

package com.example.My Application;

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

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();
   }
}

Following code will the modified content of AndroidManifest.xml file. Here we have include <service…/> tag to include our service

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.MyApplication"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="13"
      android:targetSdkVersion="22" />
   
   <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       
       <activity
          android:name=".MainActivity"
          android:label="@string/title_activity_main" >
       
          <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>

 

To add two buttons we write following content of res/layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Example of services"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
      <TextView
         android:id="@+id/textView2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Andro Development "
         android:textColor="#ff87ff09"
         android:textSize="30dp"
         android:layout_above="@+id/imageButton"
         android:layout_centerHorizontal="true"
         android:layout_marginBottom="40dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton"
        android:src="@drawable/abc"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="Start Services"
        android:onClick="startService"
        android:layout_below="@+id/imageButton"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Services"
        android:id="@+id/button"
        android:onClick="stopService"
        android:layout_below="@+id/button2"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignStart="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:layout_alignEnd="@+id/button2" />

</RelativeLayout>

 

Following will be the content of res/values/strings.xml to define two new constants:

<resources>
    <string name="app_name">My Application</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
</resources>

 

How about we attempt to run our adjusted Hello World! application we simply modified. I accept you had made your AVD while doing Android environment setup. To run the application from Android studio, open one of your task’s activity file and snap Android Studio Run Icon from the tool bar. Android Studio installs the application on your AVD and begins it and if all is well with your set-up and application, it will show taking after Emulator window

android services

To Start Android Services, let we click on Start Service button, it will start the service and as per our coding in onStartCommand() method, a messageService Started will appear on the bottom of the the simulator as given below

android services

if you wanna stop service, just click the Stop Service button.