我如何无限期地维持服务 [英] How do I keep a Service alive indefinitely

查看:56
本文介绍了我如何无限期地维持服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,该程序可以检测来自耳机插孔的音频,并在满足某些音频条件时(特别是当它检测到通过辅助音频设备刷卡时的读取情况)广播Intent.

I'm writing an app that detects audio from the headphone jack and broadcasts Intents when certain audio conditions are met (specifically when it detects the reading of a card swipe through an auxiliary audio device).

我的应用程序没有活动,只是一个应用程序和服务.

My app has no Activities, it's just an Application and a Service.

一切正常,除了在较短的时间(约一分钟)内Android清理了服务之外.

Everything works nicely except that the Service is cleaned up by Android after a relatively short time period (~ a minute).

我很好奇我要告诉Android这是一项有用的服务,除非真正需要它的内存,否则应该将其保留.我意识到我可以创建一个警报,每隔几秒钟唤醒一次,并在发现不存在时启动该服务,但是这似乎有点混乱.有没有比这更多的Android(y)方法来保持其生命力?

I'm curious what I need to do to tell Android that this is a useful Service and that it should leave it alone unless it REALLY needs its memory back. I realize that I can create an Alarm that wakes up every couple of seconds and fires up the Service if it notices that it's not there, but that seems like a kluge. Is there a more Android(y) way to keep it alive than that?

推荐答案

我的应用程序没有活动,只是一个应用程序和服务.

My app has no Activities, it's just an Application and a Service.

这意味着您的应用程序将永远不会在任何Android 3.1+设备上运行,除非您与其他将要手动启动服务的应用程序有牵连.

That means that your app will never run, on any Android 3.1+ device, unless you have some tie from some other application that is going to manually launch your service.

我正在编写一个应用程序,该应用程序可以检测来自耳机插孔的音频,并在满足某些音频条件时(特别是当它检测到通过辅助音频设备刷卡时的读取情况)广播Intent.

I'm writing an app that detects audio from the headphone jack and broadcasts Intents when certain audio conditions are met (specifically when it detects the reading of a card swipe through an auxiliary audio device).

不要用几何形状来命名您的公司-完成了.:-)

Don't name your company after a geometric shape -- it's been done. :-)

我很好奇我该怎么做才能告诉Android这是一项有用的服务,除非真正需要它的内存,否则应该将其保留.

I'm curious what I need to do to tell Android that this is a useful Service and that it should leave it alone unless it REALLY needs its memory back.

欢迎您使用 startForeground()将其声明为前台服务.折衷方案是您需要显示一个 Notification ,最好是一个允许用户停止该服务的通知.请记住,用户可能不喜欢此 Notification ,而是

You are welcome to use startForeground() to declare it to be a foreground service. The tradeoff is that you will need to show a Notification, ideally one that allows the user to stop the service. Bear in mind that users may not appreciate this Notification, but you are stuck with it, particularly on Android 4.3+. You may be better served by switching from a service to an activity, so the user can launch that, swipe a card, and process whatever the transaction is.

这篇关于我如何无限期地维持服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆