Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference to running service?

Tags:

java

android

There is a one problem - my main activity starts the service and be closed then. When the application starts next time the application should get reference to this service and stop it. But I don't know how I can get a reference to a running service. Please, I hope you can help me. Thank you.

like image 611
user1166635 Avatar asked May 07 '12 12:05

user1166635


People also ask

How do I see a list of running services on Windows?

If you ever want to see a list of running services on a local or remote Windows computer, here are 3 ways of doing it. If you are on Windows 8.1 or 10, you can use Task Manager to find all the running services. Simply switch to Service tab in Task Manager, and click the Status to sort the tab to have all running services listed together.

How to display only the services with a status of running?

This example displays only the services with a status of Running. Get-Service gets all the services on the computer and sends the objects down the pipeline. The Where-Object cmdlet, selects only the services with a Status property that equals Running. Status is only one property of service objects.

How do I add a service reference to a Windows Forms application?

In the Templates pane, select a Windows Forms Application. Enter a project name such as CallingServiceExample, and browse to a storage location. In the Solution Explorer, right-click the project name and click Add Service Reference.

How do I display only the running services in a pipeline?

If you need to display only running services, use this command: The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects only those services for which the Status parameter is set to “Running”. If you want to display only the stopped services, specify “Stopped”.


Video Answer


1 Answers

This answer is based on the answer by @DawidSajdak. His code is mostly correct, but he switched the return statements, so it gives the opposite of the intended result. The correct code should be:

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("your.service.classname".equals(service.service.getClassName())) {
            return true; // Package name matches, our service is running
        }
    }
    return false; // No matching package name found => Our service is not running
}

if(isMyServiceRunning()) {
    stopService(new Intent(ServiceTest.this,MailService.class));
}
like image 71
malexmave Avatar answered Oct 06 '22 09:10

malexmave