Tuesday, March 16, 2021

Android Service

 

Android Service Tutorial

android service

Android service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers etc. It doesn't has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

Moreover, service can be bounded by a component to perform interactivity and inter process communication (IPC).

The android.app.Service is subclass of ContextWrapper class.

Note: Android service is not a thread or separate process.

Life Cycle of Android Service

There can be two forms of a service.The lifecycle of service can follow two different paths: started or bound.

  1. Started
  2. Bound

1) Started Service

A service is started when component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method. The client can unbind the service by calling the unbindService() method.

The service cannot be stopped until all clients unbind the service.

service lifecycle

Understanding Started and Bound Service by background music example

Suppose, I want to play music in the background, so call startService() method. But I want to get information of the current song being played, I will bind the service that provides information about the current song.


Android Service Example

Let's see the example of service in android that plays an audio in the background. Audio will not be stopped even if you switch to another activity. To stop the audio, you need to stop the service.

android service example output 1

activity_main.xml

Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:

File: activity_main.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="example.javatpoint.com.androidservice.MainActivity">  
  8.   
  9.   
  10.     <Button  
  11.         android:id="@+id/buttonStart"  
  12.         android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content"  
  14.         android:layout_alignParentTop="true"  
  15.         android:layout_centerHorizontal="true"  
  16.         android:layout_marginTop="74dp"  
  17.         android:text="Start Service" />  
  18.   
  19.     <Button  
  20.         android:id="@+id/buttonStop"  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:layout_centerHorizontal="true"  
  24.         android:layout_centerVertical="true"  
  25.         android:text="Stop Service" />  
  26.   
  27.     <Button  
  28.         android:id="@+id/buttonNext"  
  29.         android:layout_width="wrap_content"  
  30.         android:layout_height="wrap_content"  
  31.         android:layout_alignParentBottom="true"  
  32.         android:layout_centerHorizontal="true"  
  33.         android:layout_marginBottom="63dp"  
  34.         android:text="Next Page" />  
  35. </RelativeLayout>  

activity_next.xml

It is the layout file of next activity.

File: activity_next.xml

It contains only one textview displaying the message Next Page

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="example.javatpoint.com.androidservice.NextPage">  
  8.   
  9.     <TextView  
  10.         android:id="@+id/textView"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content"  
  13.         android:layout_marginEnd="8dp"  
  14.         android:layout_marginStart="8dp"  
  15.         android:layout_marginTop="200dp"  
  16.         android:text="Next Page"  
  17.         app:layout_constraintEnd_toEndOf="parent"  
  18.         app:layout_constraintStart_toStartOf="parent"  
  19.         app:layout_constraintTop_toTopOf="parent" />  
  20. </android.support.constraint.ConstraintLayout>  

Service class

Now create the service implemenation class by inheriting the Service class and overridding its callback methods.

File: MyService.java
  1. package example.javatpoint.com.androidservice;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.media.MediaPlayer;  
  6. import android.os.IBinder;  
  7. import android.support.annotation.Nullable;  
  8. import android.widget.Toast;  
  9.   
  10. public class MyService extends Service {  
  11.     MediaPlayer myPlayer;  
  12.     @Nullable  
  13.     @Override  
  14.     public IBinder onBind(Intent intent) {  
  15.         return null;  
  16.     }  
  17.     @Override  
  18.     public void onCreate() {  
  19.         Toast.makeText(this"Service Created", Toast.LENGTH_LONG).show();  
  20.   
  21.         myPlayer = MediaPlayer.create(this, R.raw.sun);  
  22.         myPlayer.setLooping(false); // Set looping  
  23.     }  
  24.     @Override  
  25.     public void onStart(Intent intent, int startid) {  
  26.         Toast.makeText(this"Service Started", Toast.LENGTH_LONG).show();  
  27.         myPlayer.start();  
  28.     }  
  29.     @Override  
  30.     public void onDestroy() {  
  31.         Toast.makeText(this"Service Stopped", Toast.LENGTH_LONG).show();  
  32.         myPlayer.stop();  
  33.     }  
  34. }  

Activity class

Now create the MainActivity class to perform event handling. Here, we are writing the code to start and stop service. Additionally, calling the second activity on buttonNext.

File: MainActivity.java
  1. package example.javatpoint.com.androidservice;  
  2.   
  3. import android.content.Intent;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8.   
  9. public class MainActivity extends AppCompatActivity implements View.OnClickListener{  
  10.     Button buttonStart, buttonStop,buttonNext;  
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_main);  
  15.   
  16.         buttonStart = findViewById(R.id.buttonStart);  
  17.         buttonStop = findViewById(R.id.buttonStop);  
  18.         buttonNext =  findViewById(R.id.buttonNext);  
  19.   
  20.         buttonStart.setOnClickListener(this);  
  21.         buttonStop.setOnClickListener(this);  
  22.         buttonNext.setOnClickListener(this);  
  23.   
  24.   
  25.     }  
  26.     public void onClick(View src) {  
  27.         switch (src.getId()) {  
  28.             case R.id.buttonStart:  
  29.   
  30.                 startService(new Intent(this, MyService.class));  
  31.                 break;  
  32.             case R.id.buttonStop:  
  33.                 stopService(new Intent(this, MyService.class));  
  34.                 break;  
  35.             case R.id.buttonNext:  
  36.                 Intent intent=new Intent(this,NextPage.class);  
  37.                 startActivity(intent);  
  38.                 break;  
  39.         }  
  40.     }  
  41. }  

NextPage class

Now, create another activity.

File: NextPage.java
  1. package example.javatpoint.com.androidservice;  
  2.   
  3. import android.support.v7.app.AppCompatActivity;  
  4. import android.os.Bundle;  
  5.   
  6. public class NextPage extends AppCompatActivity {  
  7.   
  8.     @Override  
  9.     protected void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.activity_next);  
  12.     }  
  13. }  

Declare the Service in the AndroidManifest.xml file

Finally, declare the service in the manifest file.

File: AndroidManifest.xml

Let's see the complete AndroidManifest.xml file

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="example.javatpoint.com.androidservice">  
  4.   
  5.     <application  
  6.         android:allowBackup="true"  
  7.         android:icon="@mipmap/ic_launcher"  
  8.         android:label="@string/app_name"  
  9.         android:roundIcon="@mipmap/ic_launcher_round"  
  10.         android:supportsRtl="true"  
  11.         android:theme="@style/AppTheme">  
  12.         <activity android:name=".MainActivity">  
  13.             <intent-filter>  
  14.                 <action android:name="android.intent.action.MAIN" />  
  15.   
  16.                 <category android:name="android.intent.category.LAUNCHER" />  
  17.             </intent-filter>  
  18.         </activity>  
  19.         <activity android:name=".NextPage"></activity>  
  20.         <service  
  21.             android:name=".MyService"  
  22.             android:enabled="true" />  
  23.     </application>  
  24.   
  25. </manifest>  

Output:

android service example output 2 android service example output 3
android service example output 4 android service example output 5

No comments:

Post a Comment

Inapp update

  Inapp update https://desk.zoho.com/portal/vegabirdtech/en/kb/articles/how-to-use-burp-suite-with-android-mobile