为什么我不能在这个片段中创建一个通知通道?

问题描述 投票:-1回答:2

我试图在片段中创建一个通知通道,但似乎不起作用。我正在尝试制作一个浮动操作按钮,一旦按下该按钮,将会发送一条通知,该通知将仅显示文本,而不会显示其他任何内容。该通知目前不需要链接到任何活动。但是,当尝试在此片段下创建通知通道时,它将突出显示:

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和应用程序开发非常陌生,因此可以提供任何帮助。

android notifications display channel
2个回答
0
投票

[getSystemServiceContext上的方法,因此您需要使用requireContext()来获得Context,然后在其上调用getSystemService()

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

0
投票

我想出了什么问题!除了将上下文添加到getSystemService()之外,我还需要确保用于构建通知的代码和用于构建通知通道的代码的通道ID相同。

© www.soinside.com 2019 - 2024. All rights reserved.