gpt4 book ai didi

java - NotificationManagerCompat 中的 (android.content.Context) 无法应用于

转载 作者:行者123 更新时间:2023-12-02 04:26:37 24 4
gpt4 key购买 nike

我正在尝试在 fragment 中初始化NotificationManagerCompat,但显然我不能这样做,因为它需要在 Activity 中初始化。这是当我尝试在 fragment 中执行此操作时收到的代码和错误

所以我想知道的是,如果我初始化并将所有通知代码移至 MainActivity,我仍然可以从我的 fragment 中调用它吗?因为我希望每当 fragment 中的计时器完成时就触发警报。或者有不同的方法让它在我的 fragment 中工作吗?只是有点不确定如何去做这件事。谢谢!

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)

最佳答案

fragment 本身不是 Context,但它们有一个 getContext() 方法,该方法返回一个 Context 对象,您可以传递它而不是 :

notManager = NotificationManagerCompat.from(getContext());

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

关于java - NotificationManagerCompat 中的 (android.content.Context) 无法应用于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56605983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com