2011-07-03 121 views
2

我有一个活动启动服务。服务崩溃'活动'的活动

在我的活动:

startService(new Intent(this, MyService.class)); 

在我的服务,在onStart():

/* Show notification */ 
int icon = R.drawable.icon; 
tickerText = getResources().getString(R.string.app_name); 
long when = System.currentTimeMillis(); 
contentTitle = getResources().getString(R.string.app_name); 
contentText = getResources().getString(R.string.running); 

Intent notificationIntent = new Intent(this, activityClass).setAction(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
notification = new Notification(icon, tickerText, when); 
notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent); 

notification.flags = Notification.FLAG_ONGOING_EVENT; 

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); 

startForeground(0, notification); 

的服务有一个计时器,做了一些工作,每3-4分钟,并以广播信息活动如果可能。当活动结束后,该服务应该继续工作。

当我运行该应用程序,并返回到主屏幕时,该服务继续运行。但过了一段时间我得到这些logcat的消息,并且该服务停止:

07-03 16:55:09.440:信息/ ActivityManager(583):进程com.myapp(PID 11665)已经死亡。 07-03 16:55:09.440:WARN/ActivityManager(583):坠毁服务com.myapp/.MyService的计划重启在5000毫秒

我如何避免这种情况?

+0

好的,以及如何防止死亡的过程? – nhaarman

回答

2

当我运行应用程序,并返回到主屏幕,该服务继续运行。但一段时间后,我得到这些logcat消息,并停止服务......我怎样才能防止这种情况?

你一般不会说。

服务并非永久运行。太多的开发者已经开始了服务,并且从未停止过它们。而就你而言,他们这样做是没有理由的。在内存中存储服务只是看着时钟滴答是非常浪费的,尤其是因为开发者在做这样的事情时,会在Android停留时间过长后“崩溃”服务。

对您的情况,请切换到使用AlarmManager,可能与IntentService一起使用,以便在没有更多工作要完成时自动关闭服务。

+0

我试图使用AlarmManager,但如果可能,首选解决方法,因为我使用的是分析。这些都是以上下文开始和结束的,必须是相同的。关闭服务时,上下文丢失,无法关闭分析实例。还是有另一种方法来做到这一点? (我正在使用Flurry)。 – nhaarman

+0

@Niek:“或者有另一种方法可以做到这一点?” - 自己跟踪使用数据。或切换到另一个分析包,一个旨在处理服务的分析包。 – CommonsWare

1

你会想看看让你的服务运行为Remote Service,以便它在自己的进程中运行。

有关远程服务的一个博客: http://saigeethamn.blogspot.com/2009/09/android-developer-tutorial-part-9.html

样本中的一个例子: http://about-android.blogspot.com/2010/02/android-remote-service-sample.html

+0

谢谢,我会尝试。 – nhaarman

+0

这意味着应用会在活动周围占用两倍的内存,这会浪费应用程序并使其变得更糟。 – CommonsWare

+0

@CommonsWare - 活动可能不需要一直运行,但是,无论应用程序是否需要工作,并且因为活动结束而停止,则需要找到一些解决方案。 –