【发布时间】:2012-10-13 10:25:12
【问题描述】:
我目前正在创建一个前台服务,该服务启动时会在通知栏中显示一个通知。如果服务停止,通知会消失。我的问题是,有没有办法在“清除所有通知”或通知(滑动)消失时停止服务?
更新以包括通知的实现:
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(CLASS, "onStartCommand service started.");
if (getString(R.string.service_start_action) == intent.getAction())
{
Intent intentForeground = new Intent(this, ServiceMain.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(getApplicationContext(), 0, intentForeground, 0);
Notification notification;
Notification.Builder builder = new Notification.Builder(getApplicationContext())
.setSmallIcon(android.R.drawable.btn_star)
.setTicker("Service started...")
.setContentIntent(pendIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setOnlyAlertOnce(true)
.setOngoing(false);
notification = builder.build();
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
startForeground(SERV_NOTIFY, notification);
player.start();
}
else
{
Log.d(CLASS, "onStartCommand unable to identify acition.");
}
return START_STICKY;
}
【问题讨论】:
-
看看这个来自 Google 的示例:github.com/googlesamples/android-ActiveNotifications。它显示了如何侦听已关闭的通知以及整组通知。
-
据我所知,如果不创建通知,您就无法“创建”前台服务。 Android 需要这样做,因为他们不希望您在用户不知情的情况下在后台运行服务。当您的活动被破坏并且您的服务在前台运行时删除通知需要通知,您不能简单地取消它。取消通知只能通过调用'.stopForeground(true)'取消前台服务本身来完成,布尔参数表示是否要随通知一起停止前台。
标签: android android-service android-notifications