Android 为什么可以';我不能在这个片段中创建一个通知通道吗?

Android 为什么可以';我不能在这个片段中创建一个通知通道吗?,android,notifications,display,channel,Android,Notifications,Display,Channel,我试图在片段中创建一个通知通道,但它似乎不起作用。我试图使一个浮动的行动按钮,一旦按下将发送一个通知,将只显示文本,而没有其他。通知此时不需要链接到任何活动。但是,当尝试在此片段下创建通知通道时,它将突出显示: NotificationManager manager = getSystemService(NotificationManager.class); 显示为红色,表示无法解析方法getSystemService() 这是我的代码: public class NotificationsF

我试图在片段中创建一个通知通道,但它似乎不起作用。我试图使一个浮动的行动按钮,一旦按下将发送一个通知,将只显示文本,而没有其他。通知此时不需要链接到任何活动。但是,当尝试在此片段下创建通知通道时,它将突出显示:

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 studio和应用程序开发非常陌生,因此非常感谢您的帮助。

getSystemService
是一种基于
Context
的方法,因此您需要使用
requireContext()
获取
Context
,并调用
getSystemService()

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

我知道怎么了!除了将上下文添加到
getSystemService()
之外,我还需要确保用于生成通知的代码的通道ID与用于生成通知通道的代码的ID相同。

我尝试了此操作,但在运行时仍然无法工作,因为它显示了“无法在通道上发布通知”通知当按下按钮时,作为祝酒词。