我希望在 Service
类中实现 startForeground()
方法,以防止服务自我关闭。
有人能否向我发送实现此方法的代码?
我希望在 Service
类中实现 startForeground()
方法,以防止服务自我关闭。
有人能否向我发送实现此方法的代码?
final static int myID = 1234;
//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
//This constructor is deprecated. Use Notification.Builder instead
Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());
//This method is deprecated. Use Notification.Builder instead.
notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);
notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);
将这段代码放在您的service的onStartCommand()
中即可。但是,您可以将此部分代码放在service的任何位置。
附言:要停止服务处于前台状态,只需在您的service中的任何位置使用stopForeground(true);
这段代码将通过将Android支持库添加到您的项目中,使用最佳可用选项来调用任何API。在Eclipse中,您可以右键单击项目,转到Android工具,然后单击“添加支持库…”选项来下载并添加它。
final static int myID = 1234;
//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.DONUT) {
// Build.VERSION.SDK_INT requires API 4 and would cause issues below API 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("TICKER").setContentTitle("TITLE").setContentText("CONTENT")
.setWhen(System.currentTimeMillis()).setAutoCancel(false)
.setOngoing(true).setPriority(Notification.PRIORITY_HIGH)
.setContentIntent(pendIntent);
Notification notification = builder.build();
} else {
Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());
notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);
}
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notification);
将代码放在你用于服务的start方法中,当你想要停止前台进程时,在你的服务中的任何位置调用stopForeground(true);
builder.setSmallIcon(int)
。没有这个自定义构建器将被默认通知忽略。 - Konstantin Konopko我不确定这是否是您要寻找的内容,但您只需创建一个通知对象(如下所示的mOngoingNote
),并使用通知ID以及实际通知调用startForeground
即可。
startForeground(NOTEMAN_ID, mOngoingNote);