2013-03-20 16 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