Native Mobile App Development With Java

Android Service Example

15-Sep-2024

Learn how to implement background services in Android Studio Project using Java to run tasks in the background

What is a service?

Service is an application component that can perform long-running operations in the background and does not provide a user interface. Services are used for operations that need to be performed even when the user is not interacting with your application, such as handling network transactions, playing music, or interacting with content providers. 


Let's jump into an example of a service in Android

1/ First of all, we have to create a new class extending the Service class of Android. In this example, we are creating a class named MyService.


package com.akapps.serviceexample; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyService extends Service { @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "Service created", Toast.LENGTH_SHORT).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("MyService", "Service Started"); // Here we can run any operation we want // It will run in the background without the user interaction return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.d("MyService", "Service Stopped"); } @Override public IBinder onBind(Intent intent) { return null; } }

2/ Then we also need to register it in the manifest file. We are putting it inside the application component trees

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.ServiceExample" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <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>

3/ Let's add a button to start the service from the main activity

<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:gravity="center" tools:context=".MainActivity"> <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" /> </LinearLayout>

4/ Finally, we start the service from the main activity

package com.akapps.serviceexample;
import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private Button startButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); // Initialize the UI elements startButton = findViewById(R.id.start); // Set click listeners startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Start the service Intent serviceIntent = new Intent(MainActivity.this, MyService.class); startService(serviceIntent); } }); } }

Comments