Почему я не могу создать канал уведомлений в этом фрагменте? - PullRequest
0 голосов
/ 03 мая 2020

Я попытался создать канал уведомлений в моем фрагменте, но, похоже, он не работает. Я пытаюсь сделать плавающую кнопку действия, которая после нажатия отправит уведомление, которое будет отображать только текст и ничего больше. Уведомление не должно быть связано с какой-либо деятельностью в данный момент. Однако при попытке создать канал уведомления под этим фрагментом он выделит красным цветом

NotificationManager manager = getSystemService(NotificationManager.class);

, сказав, что не может разрешить метод getSystemService ().

Это мой код:

public class NotificationsFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v =  inflater.inflate(R.layout.fragment_notifications, container, false);
    //Notification channel creator
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationChannel channel = new NotificationChannel("test", "TestName", NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription("description");
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(channel);
    }

    FloatingActionButton actionButton = v.findViewById(R.id.notifications_floatingActionButton);
    actionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Write code here to execute after floating action button has been clicked:
            startActivity(new Intent(getActivity(), NotificationsEditor.class)); // starts notification editor - this is also template for starting activity in fragment
            displayNotifications();//part of notifications
        }
    });
    return v;
}

//part of notification
public void displayNotifications(){
    String ID = "notifications";
    NotificationCompat.Builder notif = new NotificationCompat.Builder(this.requireContext(), ID);
    notif.setSmallIcon(R.drawable.ic_notifications);
    notif.setContentTitle("Notification");
    notif.setContentText("Notification Example");
    notif.setPriority(NotificationCompat.PRIORITY_DEFAULT);

    NotificationManagerCompat display = NotificationManagerCompat.from(this.requireContext());
    display.notify(1, notif.build());

}//ends here

}

Я попытался создать метод для канала уведомлений в MainActivity и все еще не смог, так как уведомление не будет отображаться во время выполнения, и я также попытался создать метод для канала уведомлений в качестве метода в этом классе, и он все еще не смог отобразить уведомление во время выполнения. Я очень новичок в android разработке студий и приложений, поэтому любая помощь будет оценена.

Ответы [ 2 ]

0 голосов
/ 04 мая 2020

Я понял, что не так! Помимо добавления контекста к getSystemService() мне также нужно было убедиться, что идентификатор канала был одинаковым для кода для создания уведомления и для кода для создания канала уведомления.

0 голосов
/ 03 мая 2020

getSystemService - это метод для Context, поэтому вам нужно использовать requireContext(), чтобы получить Context, и вызвать getSystemService() для этого.

NotificationManager manager = requireContext().getSystemService(NotificationManager.class);
...