错误:getSystemServise无法解析的参考-Kotlin Android Studio

Roy*_*nin 4 android push-notification android-service kotlin

hay im new in kotlin,我尝试在我的应用中推送通知。不幸的是,我遇到这个错误:“ getSystemServise未解析的引用”这是我的代码:

        val intent = Intent()
        val pendingIntent = PendingIntent.getActivity(this.activity,0,intent,0)
        val notification = Notification.Builder(this.activity)
                .setContentTitle("time is:")
                .setContentText("text")
                .setSmallIcon(R.drawable.notification_icon_background)
                .setContentIntent(pendingIntent)

        val nm:NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(0,notification.build())
Run Code Online (Sandbox Code Playgroud)

谢谢帮手

zsm*_*b13 9

我假设您的代码在里面Fragment,这就是为什么您this.activity多次引用它的原因。作为类getSystemService()的方法Context,您需要一个Context实例来调用它。您可以使用getContext()getActivity()使用已经使用过的来获得一个(因为Activity也是Context)。

使用Kotlin的属性访问语法,这看起来像:

// either of these
this.activity.getSystemService(...)
this.context.getSystemService(...)
Run Code Online (Sandbox Code Playgroud)

甚至只是:

// either of these
activity.getSystemService(...)
context.getSystemService(...)
Run Code Online (Sandbox Code Playgroud)