我目前正在创建一个前台服务,并在服务启动时显示在通知栏中的通知。如果服务停止,通知会消失。我的问题是,有没有办法在“清除所有通知”或通知(滑动)消失时停止服务?
更新以包括通知的实施:
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;
}