Android 通知单击未调用的事件

Android 通知单击未调用的事件,android,notifications,Android,Notifications,这是在清单中声明活动的方式 <activity android:name=".view.activity.HomeActivity" android:exported="true" android:launchMode="singleTop" android:label="@string/app_name" android:theme="@style/AppTheme.Toolbar"> <intent-filter>

这是在
清单中声明活动的方式

<activity
    android:name=".view.activity.HomeActivity"
    android:exported="true"
    android:launchMode="singleTop"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.Toolbar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

但当我点击通知
onNewIntent
时,有时仅调用该通知(如果应用程序处于打开状态,我可能猜不透)。

onNewIntent
仅在活动已打开时调用,如果活动未打开,则不会调用该通知

这意味着,如果您的活动已关闭,它将正常启动,并将调用
onCreate
。 您可以在意图中传递一个标志,告诉您的活动它是从通知开始的,然后您可以在
onCreate
中找到该标志,如果该标志存在,您可以调用与
onNewIntent()中相同的函数

val intent=intent(applicationContext,HomeActivity::class.java)。应用{
flags=Intent.FLAG\u ACTIVITY\u NEW\u TASK或Intent.FLAG\u ACTIVITY\u SINGLE\u TOP
putExtra(“Id”,Id)
putExtra(“通知意图”,真);
}
在您的
OnCreate()
中:

boolean isNotificationIntent=getIntent().getExtras().getBoolean(“notificationIntent”,false);
如果(isNotificationIntent){
dosameworksonnewintent();
}

onNewIntent
仅在活动已打开时调用,如果活动未打开则不会调用。@ZohaibAmir。。那么如何解决这一问题。您的活动是否开始正确?您应该在
onCreate()
中执行与放置
onNewIntent()
onNewIntent()中相同的操作?
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    val channel = NotificationChannel("1", "MyApp", NotificationManager.IMPORTANCE_DEFAULT)
    notificationManager.createNotificationChannel(channel)
}

val notificationLayout = RemoteViews(applicationContext.packageName, R.layout.notification_view)
val notificationLayoutExpanded = RemoteViews(applicationContext.packageName, R.layout.notification_big_view)
updateLayout(notificationLayout, notificationLayoutExpanded, data)

val intent = Intent(applicationContext, HomeActivity::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
    putExtra("Id", Id)
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

val notification = NotificationCompat.Builder(applicationContext, "1")
        .setContentTitle("MyApp")
        .setSmallIcon(R.drawable.circle)
        .setCustomContentView(notificationLayout)
        .setCustomBigContentView(notificationLayoutExpanded)
        .setStyle(NotificationCompat.DecoratedCustomViewStyle())
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)

notificationManager.notify(1, notification.build())