简体   繁体   English

后台服务:当活动破坏时杀死

[英]Background Services : Kill when activity destroy

I created background service on android tab using startService() method inside the Activity . 我使用Activity startService()方法在android选项卡上创建了background service Then I create a Thread on onStart() method. 然后我在onStart()方法上创建一个Thread I read from the android developer site that service are independent of the activity, but when I destroy the Activity android system kills the service too. 我从android开发者网站上读到该服务独立于活动,但当我销毁Activity android系统也会杀死该service I want the service to continue until I do not stop it myself. 我希望服务继续,直到我自己不停止它。

I am aware that it can be done using AlarmManger but it consumes battery. 我知道它可以使用AlarmManger完成,但它消耗电池。 There is no need of push notification, but the service needs to run in the background. 不需要推送通知,但服务需要在后台运行。 Any suggestions on how to solve this? 关于如何解决这个问题的任何建议?

Use this in your service class and call it by using button 在服务类中使用它并使用按钮调用它

 @Override
    public void onDestroy() {


           Log.e("serive destroyed", "service distroyed");
        super.onDestroy();
    }

check this link for AsyncTask won't stop even when the activity has destroyed & in that check the Answer Posted By Snicolas .And take Reference of other Answers. 检查链接的AsyncTask即使在活动已经销毁时也不会停止,并在该检查中发布了Snicolas的答案。并参考其他答案。 Hope this helps. 希望这可以帮助。

It should not generally happens when activity destroys service also destroys. 当活动破坏服务也会破坏时,通常不会发生这种情况。

Services are components that run in the background, without a user interface. 服务是在后台运行的组件,没有用户界面。 More important, Android services can have life cycles separate from activities. 更重要的是,Android服务可以将生命周期与活动分开。 When an activity pauses, stops, or gets destroyed, there may be some processing that you want to continue. 当某个活动暂停,停止或被销毁时,您可能需要继续进行某些处理。 Services are good for that too. 服务也很好。

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

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