Служба stopForeground (false) удаляет уведомление, когда не следует - PullRequest
0 голосов
/ 14 ноября 2018

Вместо

stopForeground (true)

вызов,

stopForeground (false)

должно сохранять уведомление как оно есть (без текущего состояния), если оно не было отклонено пользователем / удалено программно.Это также должно предотвратить мигание уведомления, поскольку я не воссоздаю уведомление.

Но это не работает.stopForeground (false) имеет то же поведение, что и stopForeground (true).

Это пример проекта:

public class AudioTestService extends Service {
private static final String CHANNEL_ID = "TestChannel";
private static final int NOTIFICATION_ID = 14;
Notification mBuilder;

public AudioTestService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    // throw new UnsupportedOperationException("Not yet implemented");
    return null;
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    stopForeground(true);
    super.onTaskRemoved(rootIntent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Intent intentA = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intentA, 0);

    Notification mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Titolo")
            .setContentText("Descrizione")
            .setContentIntent(pendingIntent)
            .setOngoing(false)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .build();
    this.mBuilder = mBuilder;
    createNotificationChannel();
    startForeground(NOTIFICATION_ID, mBuilder);

    return START_STICKY;
}

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = CHANNEL_ID;
        String description = CHANNEL_ID + "Description ";
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

@Override
public void onDestroy() {
    stopForeground(false);
    //NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, mBuilder);
    super.onDestroy();
} }

Операция, легко обрабатывающая событие нажатия кнопки:

открытый класс MainActivity расширяет AppCompatActivity, реализует View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button startService = findViewById(R.id.startService);
    Button stopService = findViewById(R.id.stopService);
    Button stopNotification = findViewById(R.id.stopWithNotification);

    startService.setOnClickListener(this);
    stopService.setOnClickListener(this);
    stopNotification.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.startService:
            ContextCompat.startForegroundService(this, new Intent(this, AudioTestService.class));
            break;
        case R.id.stopService:
            finish();
            break;
        case R.id.stopWithNotification:
            stopService(new Intent(this, AudioTestService.class));
            break;
    }
}}

Если вы посмотрите на метод onDestroy () Службы, я установил

stopForeground (false);

вместо метода onTaskRemoved (), который должен удалять уведомление при очистке приложения из списка задач.

Что я делаю не так?

Пожалуйста, не отмечайте этокак продублировано, ищу решение по дням ...

1 Ответ

0 голосов
/ 14 ноября 2018

Вместо вызова stopForeground(false); из onDestroy() отправьте широковещательную рассылку из действия (с действием) для остановки службы.Измените код onStartCommand, чтобы проверить действие в intent и выполните startForeground или stopForeground(false);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...