问题描述
我有一个关于在片段上开始前景服务的问题.
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);
↑我知道此代码使活动开始前景服务.
所以我更改了一些用于片段上的代码
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()没有启动前景方法,我想在片段上启动前景服务.
我该怎么办?
推荐答案
在服务的onStartCommand()方法中尝试一下:
startForeground(NOTIFICATION_ID, new Notification());
可能是您需要返回START_STICKY,以保持服务运行,直到您致电selfStop().
.欢呼!
问题描述
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);
↑ 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);
and I got a problem with this :
getActivity().startForeground(1000, noti);
getActivity() doesn't have startForeground method and I want to start foreground service on fragment.
what can I do?
推荐答案
Try this in the onStartCommand() method of your service:
startForeground(NOTIFICATION_ID, new Notification());
It might be that you need to return a START_STICKY that keeps the Service running until you call selfStop().
Cheers!