简体   繁体   English

活动销毁后停止android服务

[英]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. 我正在通过setrepeating方法使用service和Alarmmanager。 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). 停止此服务的唯一方法是在我的活动屏幕上显示一个按钮(当然android系统可以随时出于任何原因将其杀死,但我不在乎android系统会做什么)。 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. 我的问题是,一段时间后我的活动被android系统破坏了,我的服务会一直运行,除非Android将其杀死。 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 . 考虑bindService和unbindService When your activity is created, you can call bindService , and use the returned binder in order to communicate with your service. 创建活动后,可以调用bindService ,并使用返回的绑定程序来与服务进行通信。 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. 另一种方法是使用LocalBroadcastManager以便在活动和服务之间进行通信。

Finally, consider either Otto or Eventbus - two awesome opensource projects for communicating between components in your android project. 最后,考虑使用OttoEventbus-两个很棒的开源项目,用于在android项目中的组件之间进行通信。

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. 在MainActivity上使用bind服务和unbind服务方法,以便在用户或android系统显式销毁您的应用活动,并同时销毁服务类时,可以调用unbind服务onDestroy()

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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