简体   繁体   中英

Stopping android service after activity destroyed

I have an application which is doing some repetitive background tasks. I'm using service and Alarmmanager with setrepeating method. The only way to stop this service is a button which appears on my activity screen (of course android system can kill it for any reason at any time but I don't care what android system does). My problem is when my activity is destroyed by android system after a while, I have a service which is running forever unless Android kills it. My question is how can I get a reference of this service to stop it after creating new activity(I assume I'm creating new activity after the old one destroyed)?.

Consider bindService and unbindService . When your activity is created, you can call bindService , and use the returned binder in order to communicate with your service. A service can be both bound and started, in case you don't want unbind to kill your service after your activity ends.

Another approach could be using a LocalBroadcastManager in order to communicate between your activity and service.

Finally, consider either Otto or Eventbus - two awesome opensource projects for communicating between components in your android project.

Use the bind service and unbind service methods on your MainActivity so that you can call unbind service onDestroy() when ever your apps activity is either explicitly destroyed by user or the android system, the service class is destroyed alongside.

Use this post as a guide: Example: Communication between Activity and Service using Messaging

I think I couldn't explain my problem clearly. But I found my answer at this post How to get reference to running service? Dawid Sajdak answer

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 false;
        }
    }
    return true;
}

if(isMyServiceRunning()) {
    stopService(new Intent(ServiceTest.this,MailService.class));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM