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.
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.
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.
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.
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”.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With