当前位置: 代码迷 >> Android >> Android服务经常停止并重新启动
  详细解决方案

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

热度:42   发布时间:2023-08-04 10:11:04.0

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

我创建了一个用于处理UI的Android服务。 一切正常,但在某些设备上,该服务非常频繁地停止,有时超过60秒后又重新启动。

我知道这是Android系统定义的行为,但是我想知道是否有一种方法可以使我的服务获得最高优先级。 这可能吗? 我的实现中有什么错误会使这种行为恶化吗?

一种选择是使您的服务成为“前台服务”,如 。 这意味着它在状态栏中显示一个图标,并可能显示一些状态数据。 报价:

前台服务是一种被认为是用户积极了解的服务,因此不适合当内存不足时被系统杀死的服务。 前台服务必须为状态栏提供一个通知,该通知位于“正在进行”标题下,这意味着除非该服务已停止或从前台删除,否则无法取消该通知。

实际上,您只需要修改Service的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 ,想法还是一样的。

  相关解决方案