【问题标题】:Android service process being killed after hoursAndroid服务进程在几个小时后被杀死
【发布时间】:2014-04-25 07:28:41
【问题描述】:

目前我正在创建一个需要始终运行的服务的程序。它运行良好,但几个小时后服务不再执行。在服务中有一个计时器,它将收集所有可用的 WiFi 网络并将其发送到服务器。

在服务不再工作并且我导航到正在 Android 中执行的应用程序后,我看到我的应用程序显示为“0 process and 1 service”(例如,Facebook 显示为“1 process and 1 service”)。这意味着该进程被终止,因此服务不再运行。我的问题是如何防止这种情况或我如何解决这个问题?我的活动绑定到服务器并在“onStartCommand”上返回“START_STICKY”。

我还阅读了一些关于 AlarmManager 的内容,但如果我理解得很好,这将每 x 秒启动一次服务。我想要的是一个服务,在我说出来之前不会停止运行,或者在进程被 Android 系统杀死后重新启动。

编辑 我不想让它成为前台服务,一种在服务停止时重新启动服务的方法对我来说很好。前台服务意味着通知栏,这不是我想要的。

编辑 2

我现在正在使用警报管理器来检查它是否正在运行:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    Intent broadcast_intent = new Intent(this, RunChecker.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  broadcast_intent, 0);

    Calendar cal = Calendar.getInstance();
    if (cal.get(Calendar.SECOND) >= 1)
        cal.add(Calendar.MINUTE, 1);
    cal.set(Calendar.SECOND, 1);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 300*1000, pendingIntent);

还有我的接收器:

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

     ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
         List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
     boolean isFind = false;
        for (RunningServiceInfo runningServiceInfo : services) {
            //Log.v("StrollSwap", runningServiceInfo.service.getClassName());
            if (runningServiceInfo.service.getClassName().equals("com.example.strollswap.StrollSwapService")){
                isFind = true;
            }
        }
        if(!isFind)
        {
            Intent startServiceIntent = new Intent(context, StrollSwapService.class);
            context.startService(startServiceIntent);
        }

}

我知道代码看起来很糟糕,但它是用于测试的,如果它按我想要的方式工作,我会重写它:)。如果有其他解决方案或解决方案肯定会起作用,请分享。

编辑编号 3

似乎编辑 2 不起作用..尚未找到解决方案。

【问题讨论】:

  • 您好,您找到这个问题的答案了吗?我目前在我的应用上遇到了同样的问题。
  • Laetan,我应用的解决方案是每隔 x 小时使用 alarmmanager 启动/重新启动服务。
  • 好的,谢谢你的帮助:)

标签: android service process


【解决方案1】:

要使您的服务永远持续,您需要将其设为“前台”服务。 请点击此链接,Running a Service in the Foreground 我希望这会对你有所帮助。

【讨论】:

  • 感谢您的回复,这可能是一个解决方案,但前台服务不是我想要的,因为这意味着我必须显示通知,这不是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多