0

我正在尝试开发一个在屏幕上绘制浮动叠加层的 Android 应用程序,就像 Facebook Messenger 和聊天头一样。

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

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

4

1 回答 1

1

一种选择是使您的服务成为“前台服务”,如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.

于 2015-10-19T08:00:55.290 回答