Services | Android App Development | Lecture#57 | Hive Learners

𝓖𝓻𝓮𝓮𝓽𝓲𝓷𝓰𝓼

Hello dear Hive Learner, In the previous lecture we learn how to update, and delete data from the Firestore. Today we will learn how the services work in Android. Services are the background task that will work behind the scenes until we manually stop them. Most of the time we use the Services for the Android Notification. Let's get started.

GitHub Link

Use this GitHub project to clone into your directory. The following lecture will update it so you will never miss the latest code. Happy Coding!

What Should I Learn

  • What are the services
  • How to implement service in your project

Assignment

  • Implement service in your project

Procedure

To implement the service we need to create an empty java class and extend it with the Service. I will create a java class MyService.java and extend it with the Service.

Now we need to override these methods.

public class MyService extends Service {


    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



}

We can also show a Toast message on Service start and on Service Stop. We also need to declare this service in the Android Manifest file.

Now we can start a stop this service. I am using the Welcom_Activity tabs to start and stop the service.

switch (position) {
                    case 0:
                        fragment = new Blogs_Fragment();
                        startService(new Intent(getBaseContext(), MyService.class));

                        break;
                    case 1:
                        fragment = new Transfers_Fragment();
                        stopService(new Intent(getBaseContext(), MyService.class));

                        break;

Let's run and check if the service is working or not. We need to change the tab to stop and start the service. We can implement it n the button press or in the activity start or destroy.


hl_divider.png

Thank You

hl_footer_banner.png

H2
H3
H4
3 columns
2 columns
1 column
3 Comments
Ecency