2015-10-19 116 views
0

我试图开发一个Android应用程序,它在屏幕上绘制一个浮动覆盖图,因为它是通过聊天头的Facebook Messenger完成的。Android服务经常停止并重新启动

我已经创建了一个处理UI的Android服务。一切运行良好,但在某些设备上,该服务非常频繁地停止,有时会在超过60秒后再次启动。

我知道这是一个由Android系统定义的行为,但我想知道是否有办法让我的服务达到最高优先级。这可能吗?这种行为会因我执行过程中的错误而变差吗?

回答

1

一种选择是使您的服务成为“前台服务”,如简要说明in Android documentation。这意味着它会在状态栏中显示一个图标和可能的一些状态数据。引用:

前台服务是一个被认为是东西 用户正在积极了解并因此不能对系统 候选人杀时内存不足的服务。前景服务必须提供状态栏,它被放置在“持续” 标题下,这意味着,该通知不能被解雇除非 服务是停止或从前景除去 通知。

实际上,您只需修改服务的onStartCommand()方法即可设置通知并致电startForeGround()。这个例子是从Android文档:

// Set the icon and the initial text to be shown. 
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis()); 
// The pending intent is triggered when the notification is tapped. 
Intent notificationIntent = new Intent(this, ExampleActivity.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
// 2nd parameter is the title, 3rd one is a status message. 
notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); 
// You can put anything non-zero in place of ONGOING_NOTIFICATION_ID. 
startForeground(ONGOING_NOTIFICATION_ID, notification); 

这实际上是建立一个通知的方式已过时,但想法是一样反正即使你使用Notification.Builder

相关问题