我有一个与 LongPoll 一起工作的服务,当我收到我的数据时一切正常,但是当我没有收到数据时,我收到的是空结果(长轮询最大时间 == 25 秒)我的服务有时会关闭手动(我没有在服务列表中看到它)。
那么,如何保持此服务(..始终..)运行?
递归函数,它与长轮询一起工作,并在服务的 onCreate()
(结构)中首次调用:
//"u" is "new utils()".
public class myservice extends Service {
public static boolean started=false;
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created qweqwe", Toast.LENGTH_LONG).show();
longpoll();
this.started=true;
}
@Override
public void onDestroy() {
super.onDestroy();
this.started=false;
}
private String url = "http://example.com/lp.php";
private void longpoll() {
try {
String resp = u.getData(url); //max time of working u.getData(lpurl) - 25s.
if (resp.length()>0) doSmthWithData(resp); //It works fine
} catch(Exception e) {}
longpoll();
}
}
最佳答案
So, how to keep this service (..always..) running?
从策略上讲,根据您问题标题中的“15 秒”,我猜您是在主应用程序线程上执行此长轮询。您需要在后台线程上执行此操作。
从战略上讲,您无法让服务“始终运行”。您可以使用 startForeground()
来降低您的服务被自动销毁的几率,但用户和操作系统仍然可以出于任何原因随时摆脱您的进程(连同其服务)。许多用户不喜欢“一直运行”的服务,因为它们浪费资源,因此会用任务 killer 和 Play 商店的低评分来攻击此类服务的开发者。
关于Android 服务在功能工作时间超过(大约)15 秒时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10861762/