(android.content.Context) 在 NotificationManagerCompat 中不能应用于



>我正在尝试在片段中初始化 NotificationManagerCompat,但实际上我无法这样做,因为它需要在活动中初始化。 这是我尝试在片段中执行此操作时收到的代码和错误

所以我想知道的是,如果我初始化并将所有通知代码移动到 MainActivity,我还能从我的片段中调用它吗?因为我希望每当片段中的计时器完成时触发警报。还是有没有其他方法可以让它在我的片段中工作?只是有点不确定如何做到这一点。谢谢!

private NotificationManagerCompat notManager;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_timer, container, false);
        notManager = NotificationManagerCompat.from(this);
//this is error I get from passing in this
(android.content.Context)
in NotificationManagerCompat cannot be applied
to
(x.gmail.com.insulincalc.TimerFragment)

片段本身不是一个Context,但它们有一个getContext()方法,它返回一个可以传递的Context对象,而不是this

notManager = NotificationManagerCompat.from(getContext());

请注意,最新版本的片段还包含一个requireContext(),它返回一个保证的非空Context。您应该考虑使用它来避免在需要非空上下文时使用可空上下文的 Lint 警告。

最新更新