Reputation: 15515
This is how activity declared in Manifest
<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>
And this is how I generate the notification
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())
But when I tap on the notification onNewIntent
called sometimes only (Maybe if app in open state, I can't guess correctly).
Upvotes: 1
Views: 1064
Reputation: 3562
onNewIntent
is only called if the activity is already open, It won't be called if the Activity is not open.
This means that if your activity was closed, it will start normally and onCreate
will be called.
You can pass a flag in your intent that tells your Activity that it was started from notification, then you find that flag in your onCreate
and if it exists, you call the same functions as you did in onNewIntent()
:
val intent = Intent(applicationContext, HomeActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
putExtra("Id", Id)
putExtra("notificationIntent", true);
}
And in your OnCreate()
:
boolean isNotificationIntent = getIntent().getExtras().getBoolean("notificationIntent", false);
if(isNotificationIntent){
DoSameWorkAsOnNewIntent();
}
Upvotes: 2