Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Java программирование > Java Мобильная разработка (Android)
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 10.09.2019, 16:38   #1
AntonCH
Пользователь
 
Регистрация: 28.11.2017
Сообщений: 58
По умолчанию Убрать notification при остановке foreground service

Запускаю сервис
Код:
Intent gpsService = new Intent(this, GPSService.class)
                        .putExtra(APP_PREFERENCES_TOKEN, authData.getToken())
                        .putExtra(APP_PREFERENCES_KEY, authData.getKey())
                        .putExtra(APP_PREFERENCES_DELAY, authData.getKey())
                        .putExtra("updateUrl", authData.getBaseUrl());

                gpsService.setAction("com.truiton.foregroundservice.action.startforeground");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(new Intent(this, GPSService.class)
                        .putExtra("token", authData.getToken()).putExtra("key",authData.getKey()));
                } else {
                    startService(gpsService);
                }
При старте показываю уведомление
Код:
void sendNotif() {
        Intent resultIntent = new Intent(this, MainActivity.class);
        notificationId = (int)(System.currentTimeMillis()%10000);
        resultIntent.putExtra("notif_id", notificationId);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher_foreground)
                        .setContentTitle("Навигатор")
                        .setContentText("Идет передача координат")
                        .setContentIntent(resultPendingIntent);

        Notification notification = builder.build();
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(notificationId, notification);
    }
в методе события удаления сервиса пытаюсь удалить уведомление
Код:
  @Override
    public void onDestroy() {
        super.onDestroy();
        executor.shutdown();
        stopForeground(true);
        MainActivity.isServiceAlive = false;
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(notificationId);
    }
Но уведомление никуда не исчезает. Как его удалить?
AntonCH вне форума Ответить с цитированием
Старый 10.09.2019, 17:46   #2
AntonCH
Пользователь
 
Регистрация: 28.11.2017
Сообщений: 58
По умолчанию

Помогло следующее
Код:
    @Override
    public void onDestroy() {
        super.onDestroy();
        executor.shutdown();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
            notificationManager.cancel(notificationId);
            notificationManager.cancelAll();
        }
        else{
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            notificationManager.notify(notificationId, builder.build());
        }
        MainActivity.isServiceAlive = false;
        stopSelf();
    }
AntonCH вне форума Ответить с цитированием
Старый 20.09.2019, 18:15   #3
AntonCH
Пользователь
 
Регистрация: 28.11.2017
Сообщений: 58
По умолчанию

Код:
void sendNotif() {
        Intent intent = new Intent(MainActivity.BROADCAST_ACTION);
        try{
            Intent resultIntent = new Intent(this, MainActivity.class);
            notificationId = 777;
            PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel();
                Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                        .setSmallIcon(R.mipmap.ic_launcher_foreground)
                        .setContentTitle("Навигатор")
                        .setContentText("Идет передача координат")
                        .setContentIntent(resultPendingIntent);
                Notification notification = builder.build();
                startForeground(notificationId, notification);
            }
            else{
                NotificationCompat.Builder builder =
                        new NotificationCompat.Builder(this)
                                .setSmallIcon(R.mipmap.ic_launcher_foreground)
                                .setContentTitle("Навигатор")
                                .setContentText("Идет передача координат")
                                .setContentIntent(resultPendingIntent);

                Notification notification = builder.build();
                notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;

                NotificationManager notificationManager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                notificationManager.notify(notificationId, notification);
            }
        }catch(Exception e){
            Log.e("SERVICE GPS ERROR - ",e.toString());
            intent.putExtra("Error", false);
            intent.putExtra("Result", e.toString());
            sendBroadcast(intent);
        }
    }
AntonCH вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Azure Service Fabric: не запускается local Service Fabric Cluster Glen Общие вопросы .NET 0 30.05.2016 20:01
Azure Service Fabric: не запускается Microsoft Service Fabric Host Service Glen Общие вопросы .NET 0 28.05.2016 22:00
узнать активно ли (foreground) приложение Obert Помощь студентам 3 20.05.2010 02:53
Вопрос по остановке програмы VirusOfLove Помощь студентам 3 20.11.2009 16:19
OpenProcessToken для процессов LOCAL SERVICE и NETWORK SERVICE M.A.R.K Win Api 12 04.05.2008 09:51