Как работать с уведомлениями

Рейтинг: 1Ответов: 0Опубликовано: 21.03.2023

Возникла проблема при создании Уведомлений во Фрагменте при нажатии на кнопку, точнее с разрешениями на них, я полагаю.

Я пытаюсь реализовать уведомления в тестовом приложении. По статьям из документации пытаюсь восстановить логическую цепочку, но не получается. ЭТО ВСЕ СДЕЛАНО ВО ФРАГМЕНТЕ!

Итак, сначала я добавляю необходимую зависимость.

implementation 'androidx.core:core-ktx:1.9.0'

Затем я изменяю файл манифеста:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" >
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

    <application

В моем Фрагменте я объявляю функцию добавления канала:

private String CHANNEL_ID = "channelid";

private void createNotificationChannel() {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = getContext().getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }

Этот метод вызывается в onViewCreated.

Уведомление должно появиться при нажатии кнопки, поэтому (onViewCreated):

mainFragmBinding.notifications.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(getContext(),
                        Manifest.permission.POST_NOTIFICATIONS) ==
                        PackageManager.PERMISSION_GRANTED) {
                    showNotification();
                } else {

                }
            }
        });

showNotification():

private void showNotification() {
        NotificationCompat.Builder builder = new
                NotificationCompat.Builder(getContext(), CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle(getString(
                        R.string.notification_title))
                .setContentText(notificationText)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        NotificationManagerCompat notificationManager =
                NotificationManagerCompat.from(getContext());
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {

            }
        notificationManager.notify(
                42, builder.build()
        );
            return;
        }

Далее, как я полагаю, нужно определить логику, а что делать, если разрешение не дано?

if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {

            }

Но требуемый (?) метод устарел:

@Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE &&
                grantResults.length == 1) {
            if (
                    grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) {
            }
        }
        super.onRequestPermissionsResult(
                requestCode, permissions, grantResults
        );
    }

Возможно, в if нужно вызвать этот метод:

public void requestPermissions() {
        ActivityCompat.requestPermissions(getActivity(),
                new String[] {
                        Manifest.permission.POST_NOTIFICATIONS
                },
                PERMISSION_REQUEST_CODE);
    }

Где ошибка и как быть дальше? Помогите, пожалуйста!

Мне нужны обычные уведомления на данный момент.

Ответы

Ответов пока нет.