To perform operations on the background, Android service is used which is not a thread or separate process. It is a component used for playing music, handling the network transactions, interacting content providers, etc. Without any UI (user interface), the Android service runs in the background indefinitely even after the application is destroyed. To perform interactivity and inter-process communication (IPC), the Android service can be bounded by a component. The ContextWrapper class has the android.app.Service as a subclass.
Life Cycle of the Android Service:
A service can have two forms, i.e., the lifecycle of service can follow two different paths These are:
- Started
- Bound
Started Service:
When a component (like activity) calls the startService() method, the Android service starts which runs in the background indefinitely. It is stopped by The stopService() method is used to stop the service. The stopSelf() method is called by the service to stop itself.
Bound Service:
The bindService() method is called by another component (e.g. client) to bind the service. The unbindService() method can be called by the client to unbind the service. Until all the clients unbind the service, the service cannot be stopped.
Understanding Started and Bound Service by background music:
For Example: To play music in the background, we can call the startService() method. But to get the information about the current song being played, the service that provides information about the current song is required to be bound.
Android Service Example:
In the below example, we are demonstrating the usage of the service in android to play audio in the background. Even after switching to another activity, the Audio will not be stopped. We need to stop the service to do so.
activity_main.xml:
In the activity_main.xml, we will drag the 3 buttons from the palette.
<?xml version="1.0" encoding="utf-8"?> <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" tools:context="com.example.radioapp.MainActivity"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Example" 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="Hello World" 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/php" 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> |
Service class:(File: MyService.java)
By inheriting the Service class and overriding the callback methods of the Service class we will create the service implementation class.
package com.example.radioapp; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.widget.Toast; public class MyService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { 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(); } } |
Activity class:(File: MainActivity.java)
In the MainActivity class, we will perform the event handling, i.e, we will write the code to start and stop the service. In the MainActivity class, we will also call the second activity on the buttonNext.
package com.example.radioapp; import android.content.Intent; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.View; public class MainActivity extends Activity { String msg = "Android : "; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(msg, "The onCreate() event"); } 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)); } } |
AndroidManifest.xml:
In the AndroidManifest.xml file, we will declare the service.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.radioapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" 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" /> </application> </manifest> |
Output 1:
Output 2:
Output 3: