Skip to content

Commit

Permalink
Fixed deep linking issue on background app
Browse files Browse the repository at this point in the history
Notification permissions on Android 12+
  • Loading branch information
s1g53gv committed Dec 17, 2024
1 parent 15fe865 commit 0fb97fc
Show file tree
Hide file tree
Showing 9 changed files with 126 additions and 42 deletions.
10 changes: 10 additions & 0 deletions .idea/deploymentTargetSelector.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ SPDX-License-Identifier: CC0-1.0
package="it.bz.noi.community">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<queries>
<intent>
<action android:name="android.intent.action.DIAL" />
Expand Down
47 changes: 47 additions & 0 deletions app/src/main/java/it/bz/noi/community/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
package it.bz.noi.community

import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.asLiveData
Expand Down Expand Up @@ -45,6 +49,17 @@ class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

if (intent.hasExtra("deep_link")) {
val deepLink = intent.getStringExtra("deep_link")
if (deepLink != null) {
val uri = Uri.parse(deepLink)
startActivity(Intent(Intent.ACTION_VIEW).apply { data = uri })
finish()
return
}
}

window.navigationBarColor = resources.getColor(R.color.background_color, theme)

binding = ActivityMainBinding.inflate(layoutInflater)
Expand Down Expand Up @@ -144,6 +159,38 @@ class MainActivity : AppCompatActivity() {
MessagingService.registrationToken()
}
subscribeToNewsTopic(Utils.getPreferredNoiNewsTopic())

checkNotificationPermission()
}

/**
* Very crude solution to quick add notification permission.
*/
private fun checkNotificationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ActivityCompat.checkSelfPermission(
this,
android.Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
0
)
}
}
}

override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 0 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Notification permission granted")
}
}

private fun subscribeToNewsTopic(preferredNewsTopic: String) {
Expand Down
18 changes: 14 additions & 4 deletions app/src/main/java/it/bz/noi/community/SplashScreenActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,20 @@ class SplashScreenActivity : AppCompatActivity() {

private fun goToMainActivity() {
if (isFinishing) return
startActivity(Intent(this, MainActivity::class.java).apply {
putExtra(MainActivity.EXTRA_SHOW_WELCOME, runBlocking { !getWelcomeUnderstood() })
})
finish()
if (intent.hasExtra("deep_link")) {
val deepLink = Uri.parse(intent.getStringExtra("deep_link"))
startActivity(Intent(this, MainActivity::class.java).apply {
setData(deepLink)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
putExtra(MainActivity.EXTRA_SHOW_WELCOME, false)
})
finish()
} else {
startActivity(Intent(this, MainActivity::class.java).apply {
putExtra(MainActivity.EXTRA_SHOW_WELCOME, runBlocking { !getWelcomeUnderstood() })
})
finish()
}
}

private fun goToOnboardingActivity() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.firebase.messaging.ktx.messaging
import it.bz.noi.community.MainActivity
import it.bz.noi.community.R
import it.bz.noi.community.ui.NewsTickerFlow
import kotlin.random.Random


class MessagingService : FirebaseMessagingService() {

override fun onNewToken(token: String) {
Expand All @@ -41,43 +43,63 @@ class MessagingService : FirebaseMessagingService() {
}
}

private fun showNotificationBanner(message: CharSequence, title: CharSequence, link: Uri) {
with (NotificationManagerCompat.from(this)) {
val id = Random.nextInt()
companion object {
private const val TAG = "MessagingService"
private const val CHANNEL_ID = "newsChannel"

val newsOrEventDetailsPendingIntent = PendingIntent.getActivity(
applicationContext,
0,
Intent(Intent.ACTION_VIEW).apply { data = link },
PendingIntent.FLAG_IMMUTABLE
fun Context.showNotification() {
showNotificationBanner(
"Test",
"Test",
Uri.parse("noi-community://it.bz.noi.community/eventDetails/2343242")
)
}

val notification = NotificationCompat.Builder(this@MessagingService, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(newsOrEventDetailsPendingIntent)
.build()

try {
notify(id, notification)
} catch (e: SecurityException) {
Log.e(TAG, "No permission granted", e)
private fun Context.showNotificationBanner(
message: CharSequence,
title: CharSequence,
link: Uri
) {
with(NotificationManagerCompat.from(this)) {
val id = Random.nextInt()

val newsOrEventDetailsPendingIntent = PendingIntent.getActivity(
applicationContext,
0,
Intent(this@showNotificationBanner, MainActivity::class.java).apply {
data = link
flags = Intent.FLAG_ACTIVITY_NEW_TASK
},
PendingIntent.FLAG_IMMUTABLE
)

val notification =
NotificationCompat.Builder(this@showNotificationBanner, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(newsOrEventDetailsPendingIntent)
.build()

try {
notify(id, notification)
} catch (e: SecurityException) {
Log.e(TAG, "No permission granted", e)
}
}
}
}

companion object {
private const val TAG = "MessagingService"
private const val CHANNEL_ID = "newsChannel"

@JvmStatic
fun createChannelIfNeeded(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
with (NotificationManagerCompat.from(context)) {
with(NotificationManagerCompat.from(context)) {
val channelName = context.getString(R.string.news_notification_channel_name)
val channel = NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH)
val channel = NotificationChannel(
CHANNEL_ID,
channelName,
NotificationManager.IMPORTANCE_HIGH
)
createNotificationChannel(channel)
}
}
Expand All @@ -93,7 +115,7 @@ class MessagingService : FirebaseMessagingService() {
// Get new FCM registration token
val token = task.result

val msg ="FCM registration token: $token"
val msg = "FCM registration token: $token"
Log.d(TAG, msg)
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ class EventDetailsFragment : Fragment(), EventClickListener {
val events = it.data
if (!events.isNullOrEmpty()) {
allEvents = events as ArrayList<EventsResponse.Event>
selectedEvent = events[args.eventIndex]
selectedEvent = events.firstOrNull { event -> event.eventId == args.eventId }
?: events.first()

(requireActivity() as AppCompatActivity).supportActionBar?.title =
getEventName(selectedEvent)
Expand Down Expand Up @@ -362,8 +363,7 @@ class EventDetailsFragment : Fragment(), EventClickListener {

findNavController().navigate(
EventDetailsFragmentDirections.actionEventDetailsFragmentSelf(
null,
allEvents.indexOf(event)
event.eventId,
),
extras
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,7 @@ class EventsFragment : Fragment(), EventClickListener, TimeFilterClickListener {
)
findNavController().navigate(
TodayFragmentDirections.actionNavigationTodayToEventDetailsFragment(
null,
todayViewModel.events.indexOf(event)
event.eventId,
),
extras
)
Expand Down
4 changes: 0 additions & 4 deletions app/src/main/res/navigation/mobile_navigation.xml
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,6 @@ SPDX-License-Identifier: CC0-1.0
android:name="eventId"
app:argType="string"
app:nullable="true" />
<argument
android:name="eventIndex"
app:argType="integer"
app:nullable="false"/>
<action
android:id="@+id/action_eventDetailsFragment_self"
app:destination="@id/eventDetailsFragment" />
Expand Down

0 comments on commit 0fb97fc

Please sign in to comment.