Home » Android » How to start a android service from one activity and stop service in another activity?

How to start a android service from one activity and stop service in another activity?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I need to start an android service from activity and stop the activity and stop service from other activity.

any help will be appreciated

How to&Answers:

A service skeleton:

public class MyService extends Service {
    public static final String TAG = "MyServiceTag";
    ...
}

This is part of the starting activity:

processStartService(MyService.TAG);

private void processStartService(final String tag) {
    Intent intent = new Intent(getApplicationContext(), MyService.class);
    intent.addCategory(tag);
    startService(intent);
}

This is part of the stopping activity:

processStopService(MyService.TAG);

private void processStopService(final String tag) {
    Intent intent = new Intent(getApplicationContext(), MyService.class);
    intent.addCategory(tag);
    stopService(intent);
}

Answer:

How to start/stop android service?

startService(intent) or stopService(intent)

These functions can be called from any activity.

How to stop an activity? – By this i understand that you need to navigate away from this activity. The function call

finish()

would remove the activity from the activity stack.