安卓 Kotlin : Required Context but found String

标签 android kotlin

我正在尝试创建一个安排通知的方法。在该方法中,我初始化了 AlarmManager这将使我能够按需接收 Intent。但是,我的代码中出现以下语法错误:

Type mismatch. Required: Context Found: String



在以下行:
 var alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

下面是我的代码:
package com.example.notificationapp

import android.app.AlarmManager
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.getActivity
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat.getSystemService
import java.security.AccessController.getContext
import java.util.*

// Channel

class Notification(context:Context, notificationManager: NotificationManager, title:String, description:String, date: Date) {
    // Attributes
    private lateinit var context:Context;
    private var title:String = ""
    private var description:String = ""
    private lateinit var date:Date;
    private lateinit var notificationManager:NotificationManager;

    // Initialization
    init {
        // Download the constructor parameters into the object's attributes
        this.context = context
        this.title = title
        this.description = description
        this.date = date
        this.notificationManager = notificationManager
    }

    // Method to set the notification at a specific time
    fun setNotificationAtTime(time:Date) {
        var notificationIntent = Intent(this.context, NotificationBroadcast::class.java)
        var pendingNotificationIntent = PendingIntent.getBroadcast(this.context,
            0, notificationIntent, 0)

        // Initialize an AlarmManager that allows us to receive intents on demand
        var alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

        val builder = NotificationCompat.Builder(context, "com.example.notificationapp")
    }
}

最佳答案

这是因为您使用的是 ContextCompat.getSystemService而不是 Context.getSystemService .

所以你在这里有两个选择:

  • 使用ContextCompat.getSystemService使用正确的签名:

  • getSystemService(context, AlarmManager::class.java)
    
  • 使用Context.getSystemService删除导入语句:

  • androidx.core.content.ContextCompat.getSystemService
    

    关于安卓 Kotlin : Required Context but found String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61709097/

    相关文章:

    android - 操作系统错误 : No such file or directory, 错误编号 = 2 -- FLUTTER

    android - 将 json 文件导入到 firebase 中的实时数据库的替代方法

    android - 如何在Flutter中将CircularProgressIndicator放入另一个CircleProgressIndicator中?

    使用运算符的 Kotlin Map

    android - Kotlin流程: callbackFlow with lazy initializer of callback object

    spring-boot - Kotlin Springboot 应用程序无法找到 Azure Application Insight 的连接字符串

    kotlin - 是否可以动态更改实例的方法?

    c# - 按钮单击Xamarin Android项目仅工作一次

    android - 无法在 Android (Kotlin) 中使用 ObjectBox 保存相同的数据

    android - 使用加速度计计算旋转矩阵