2013-03-20 15 views
2

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

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方法,我想开始前景服务片段。

我该怎么办?

回答

1

试试这个在您的服务onStartCommand()方法:

startForeground(NOTIFICATION_ID, new Notification()); 

这可能是你需要返回START_STICKY,保持运行,直到您叫selfStop()服务。

干杯!

+0

哦,我的天,问题解决了。谢谢! :d – Vinckel 2013-03-22 11:29:12