[JAVA] Stop Service and timer

Described because the service to take screenshots on a regular basis did not end in the middle. Services with timer processing stop the service after the timer stops (Even if only the service is stopped, the timer keeps running behind the scenes and the process remains). Here, the task (timer) defined in Service is canceled and stopped by stopService.

When confirming the start of the service, true will continue to pass unless the timer is stopped.

Service name: Service

Activity.java


        //Timer processing confirmation
        SService ssservice= new SService();
        if(ssservice.task != null) {
            ssservice.task.cancel();
            ssservice.task = null;
        }

        //Service outage
        android.content.Intent _intent;
        _intent = new android.content.Intent(getApplicationContext(), ssservice.class);
        getApplicationContext().stopService(_intent);

You can check the start of the service with the following sources. Please for reference

Activity.java


private boolean isMyServiceRunning(Class<?> serviceClass) {
        //Service start confirmation
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                //Service started
                return true;
            }
        }
        //Service is not started
        return false;
}

Recommended Posts

Stop Service and timer
docker-compose down and stop
Note: [Docker] How to start and stop