Android-如何在片段上启动前台服务?
问题描述:
我有一个关于在片段上启动前台服务的问题.
I have a question about starting foreground service on fragment.
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上启动前台服务.
↑ I know this code makes start foreground service on Activity.
所以我更改了一些用于片段的代码
so I changed some code for use on fragment
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方法,我想在片段上启动前台服务.
getActivity() doesn't have startForeground method and I want to start foreground service on fragment.
我该怎么办?
答
在服务的onStartCommand()
方法中尝试以下操作:
Try this in the onStartCommand()
method of your service:
startForeground(NOTIFICATION_ID, new Notification());
可能是您需要返回START_STICKY
来保持服务运行,直到您调用selfStop()
.
It might be that you need to return a START_STICKY
that keeps the Service running until you call selfStop()
.
干杯!