簡體   English   中英

NotificationManagerCompat中的(android.content.Context)無法應用於

[英](android.content.Context) in NotificationManagerCompat cannot be applied to

我正在嘗試在片段中初始化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());

請注意,更新版本的Fragments還包含requireContext() ,它返回有保證的非null Context 當需要非空上下文時,您應該考慮使用它來避免有關使用可空上下文的Lint警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM