在Activity中启动前台服务

5

如何在Activity中启动服务?

我尝试调用:

Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name),System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.app_name),getText(R.string.app_name), pendingIntent);
    startForeground(1, notification);

然而,它会显示"Cannot resolve method 'startforeground(int, android.app.Notification)'"。

我该怎么调用startForeground方法呢?我尝试使用getApplicationContext()但没有成功。

1个回答

10
如何在Activity中启动一个服务?
调用 startService()
但是,“Cannot resolve method 'startforeground(int, android.app.Notification)'”。 startForeground()Service 的一个方法。你的 Service 需要在自己上面调用 startForeground()(例如,在服务的 onCreate() 中)。

那我需要一个单独的类来管理通知吗?并且它必须扩展服务吗? - waylonion
1
@WayWay:你问题中的所有代码都应该放在一个“服务”中。更重要的是,只有当你需要将一个“服务”设置为前台优先级时才运行该代码。前台服务可能会对用户体验产生不利影响(例如,导致你的进程占用系统内存)。只有当用户能够理解你的服务正在运行以及你为什么调用了startForeground()方法时,才使用它们。 - CommonsWare
谢谢,我现在理解了Service的机制。 - waylonion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接