2

我有一个关于在片段上启动前台服务的问题。

Intent intent = new Intent(this, MainActivity.class);  
PendingIntent pendingIndent = PendingIntent.getActivity(this, 1, intent, 0);  
Notification mNotification = new Notification(R.drawable.ic_music, msg, System.currentTimeMillis());  
mNotification.setLatestEventInfo(this, title, msg, pendingIndent);  
mNotification.flags = mNotification.flags|Notification.FLAG_ONGOING_EVENT;  
startForeground(1000, mNotification);

↑ 我知道这段代码会在 Activity 上启动前台服务。

所以我更改了一些用于片段的代码

Intent intent = new Intent(getActivity(), xxx.class);  
PendingIntent pendingIndent = PendingIntent.getActivity(getActivity(), 1, intent, 0);  
Notification noti = new Notification(R.drawable.ic_xxx, "xx", System.currentTimeMillis());  
noti.setLatestEventInfo(getActivity(), "title", "xx", pendingIndent);  
noti.flags = noti.flags|Notification.FLAG_ONGOING_EVENT;  
getActivity().startForeground(1000, noti); 

我遇到了这个问题:

getActivity().startForeground(1000, noti);

getActivity() 没有 startForeground 方法,我想在片段上启动前台服务。

我能做些什么?

4

1 回答 1

0

在您的服务方法中尝试此onStartCommand()操作:

startForeground(NOTIFICATION_ID, new Notification());

您可能需要返回一个START_STICKY保持服务运行的 a,直到您调用selfStop().

干杯!

于 2013-03-20T07:52:04.757 回答