【问题标题】:Why can't I create a notification channel in this fragment?为什么我不能在这个片段中创建通知通道?
【发布时间】:2020-08-18 04:12:18
【问题描述】:

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

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      getSystemServiceContext上的一个方法,所以你需要使用requireContext()得到一个Context,然后调用getSystemService()

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

      【讨论】:

      • 我试过了,但它在运行时仍然不起作用,因为当按下按钮时,它显示“未能在频道“通知”上发布通知作为 toast 消息。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 2019-10-30
      相关资源
      最近更新 更多