Android服务经常停止并重新启动

时间:2015-10-19 07:15:34

标签: android android-service facebook-messenger

我正在尝试开发一个在屏幕上绘制浮动叠加层的Android应用程序,因为它是由Facebook Messenger与聊天头完成的。

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

我知道这是Android系统定义的行为,但我想知道是否有办法让我的服务具有最高优先级。这可能吗?我的实现中的某些内容是错误的会导致这种行为恶化吗?

1 个答案:

答案 0 :(得分: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,这个想法也是一样的。

相关问题