What is an Android Service?
Android service is a component that is used to perform operations in the background such as playing music, handle network transactions, interacting with content providers, etc. It doesn’t have any UI (user interface).
The service runs in the background indefinitely even if an application is destroyed.
Note: Android service is not a thread or separate process.
Life Cycle of Android Service:-
There can be two forms of service.
- Started
- Bound
Basics of an Android Service
Creating a Service
>> To create service we will create a normal class extending the class Service. And we should override the following methods.
onStartCommand()
>> This method is invoked when the service is started using the startService() method. We can call the method startService() from any activity and it will request the service to start.
onBind()
>>If it is needed to bind the service with an activity this method is called. The service can result back something to the activity after binding. But if you do not want to bind the service with activity then you should return null on this method.
onCreate()
>>This method is called when the service is created.
onDestroy()
>>When the service is no longer used and destroyed this method is called by the system.
Defining it on Manifest
>>You need to define your service in your AndroidManifest.xml file. It is very important.
<service android:enabled="true" android:name=".YourServiceName" />
Android Service Example:-
Step 1:- Creating User Interface
-
Once the project is loaded come inside activity_main.xml and create the following layout.
-
For the above UI, you can use the following XML 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:background="#000000" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <Button android:id="@+id/Start_Service" android:layout_width="200dp" android:layout_height="wrap_content" android:text="Start Service"/> <Button android:id="@+id/Stop_Service" android:layout_width="200dp" android:layout_height="wrap_content" android:text="Stop Service"/> </LinearLayout> </LinearLayout>
-
Now we will code the MainActivity.java as below.
package com.thecodehubs.androidserviceexample; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button Start_Service,Stop_Service; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Start_Service=findViewById(R.id.Start_Service); Start_Service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startService(new Intent(getApplicationContext(), MyService.class)); } }); Stop_Service=findViewById(R.id.Stop_Service); Stop_Service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopService(new Intent(getApplicationContext(), MyService.class)); } }); } }
-
Now we will create our service.
-
package com.thecodehubs.androidserviceexample; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.provider.Settings; import androidx.annotation.Nullable; public class MyService extends Service { private MediaPlayer player; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //getting systems default ringtone player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI); //setting loop play to true //this will make the ringtone continuously playing player.setLooping(true); //staring the player player.start(); //we have some options for service //start sticky means service will be explicitly started and stopped return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); //stopping the player when service is destroyed player.stop(); } }
-
Defining Service in Manifest.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.thecodehubs.androidserviceexample"> <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/Theme.AndroidServiceExample"> <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:enabled="true" android:name=".MyService" /> </application> </manifest>
-
Now you can run your project. When you will tap on Start Service ringtone will start ringing. And even if you close your application ringtone will keep ringing. Because it is playing with a Service that runs in the background. To stop it you have to stop the service using the Stop Service button.
Congratulations!!! you have developed your Android Service Example for Background Processes in Android Studio and now just keep following the rest of the tutorial step by step to become a great Android Developer. All the very best.
Problem : ek bar start click and stop click se perfectly chalta haii lekin many time start click karne se stop bhi nahi ho raha or many time rington,alarm,etc baj ke sunay de raha hai …….