创建意向会产生"Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()



我正在尝试按照Google上的代码在Wear OS设备上创建通知。

import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.NotificationCompat.WearableExtender
class MainActivity : WearableActivity() {

val notificationId = 1
// The channel ID of the notification.
val id = "my_channel_01"
// Build intent for notification content
val viewPendingIntent = Intent(this, com.alborz.innout.MainActivity::class.java).let { viewIntent ->
viewIntent.putExtra(EXTRA_EVENT_ID, notificationId)
PendingIntent.getActivity(this, 0, viewIntent, 0)
}
// Notification channel ID is ignored for Android 7.1.1
// (API level 25) and lower.
val notificationBuilder = NotificationCompat.Builder(this, id)
.setLocalOnly(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("TITLE")
.setContentText("TEXT")
.setContentIntent(viewPendingIntent)

稍后我尝试激活通知,如下所示:

button_in.setOnClickListener {
NotificationManagerCompat.from(this).apply {
notify(notificationId, notificationBuilder.build())
}
}

但是我得到了一个我不明白的错误。(我对 Kotlin 超级陌生,所以可能错过了一些明显的东西(

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.alb.innout/com.alb.innout.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2844)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:142)
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:6082)
at com.alb.innout.MainActivity.<init>(MainActivity.kt:46)

46号线val viewPendingIntent = Intent ...

应将此意向和通知设置放在函数中,并在发送通知时调用该函数。按照您现在的方式,Intent 是在实例化 Activity 时创建的,这在onCreate()Activity 实例化之前,对于它作为想要使用其 Context 的函数和构造函数的this参数传递还为时过早。

相关内容