Как остановить андроид сервис с через уведомление?
Как остановить сервис андроид через уведомление?
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID )
.setContentTitle("Alarm")
.setContentText(getString(R.string.n_text) + alarmHour.toString() + " : " + minute_string)
.setSmallIcon(R.drawable.ic_stat_name)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build();
Ответы (1 шт):
Автор решения: Сергей Бувака
→ Ссылка
По нажатию на нотификашку вы должны отправлять интент в сервис, при получении которого сервис будет сам себя завершать.
Вот примерно так это должно выглядеть.
Intent intent = new Intent(context, MusicNotificationBroadcastReceiver.class);
intent.setAction("STOP_ACTION");
PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Hello")
.setTicker("Hello 2")
.setContentText("Hello 3")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(contentIntent)
.setOngoing(true)
.build();
И соответственно в onStartCommand обработать этот интент
if(intent.getAction() != null && intent.getAction().equals("STOP_ACTION")) {
stopForeground(true);
}