Skip to content

Commit

Permalink
refactor(onesignal): upgrade OneSignal to 5.x and remove "OneSignal a…
Browse files Browse the repository at this point in the history
…nd Broadcast" tutorial
  • Loading branch information
ImaginativeShohag committed Jul 31, 2024
1 parent b27598c commit db44f8b
Show file tree
Hide file tree
Showing 10 changed files with 98 additions and 124 deletions.
2 changes: 1 addition & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ android {
minSdk = BuildConfigConst.minSdk
targetSdk = BuildConfigConst.targetSdk
versionCode = (findProperty("android.injected.version.code") as? String)?.toIntOrNull() ?: 1
versionName = "7.0.0.${getCurrentDateAsYYMMDD()}" // Major.Minor.Patch.YYMMDD
versionName = "7.1.0.${getCurrentDateAsYYMMDD()}" // Major.Minor.Patch.YYMMDD
vectorDrawables.useSupportLibrary = true

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
Expand Down
20 changes: 12 additions & 8 deletions app/src/main/kotlin/org/imaginativeworld/whynotcompose/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ import android.app.Application
import com.google.android.gms.maps.MapsInitializer
import com.google.android.gms.maps.OnMapsSdkInitializedCallback
import com.onesignal.OneSignal
import com.onesignal.debug.LogLevel
import dagger.hilt.android.HiltAndroidApp
import org.imaginativeworld.whynotcompose.utils.onesignal.MyNotificationOpenedHandler
import org.imaginativeworld.whynotcompose.utils.onesignal.MyNotificationWillShowInForegroundHandler
import org.imaginativeworld.whynotcompose.utils.onesignal.MyNotificationClickListener
import org.imaginativeworld.whynotcompose.utils.onesignal.MyNotificationLifecycleListener
import timber.log.Timber

@HiltAndroidApp
Expand All @@ -45,19 +46,22 @@ class App :
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())

OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE)
OneSignal.Debug.logLevel = LogLevel.VERBOSE
} else {
OneSignal.Debug.logLevel = LogLevel.NONE
}

// New Map Renderer
MapsInitializer.initialize(applicationContext, MapsInitializer.Renderer.LATEST, this)

// OneSignal
OneSignal.initWithContext(this)
OneSignal.setAppId(ONESIGNAL_APP_ID)
OneSignal.setNotificationWillShowInForegroundHandler(
MyNotificationWillShowInForegroundHandler(this)
OneSignal.initWithContext(this, ONESIGNAL_APP_ID)
OneSignal.Notifications.addForegroundLifecycleListener(
MyNotificationLifecycleListener(this)
)
OneSignal.Notifications.addClickListener(
MyNotificationClickListener(this)
)
OneSignal.setNotificationOpenedHandler(MyNotificationOpenedHandler(this))
}

override fun onMapsSdkInitialized(renderer: MapsInitializer.Renderer) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@ import org.imaginativeworld.whynotcompose.ui.screens.tutorial.navdatapass.NavDat
import org.imaginativeworld.whynotcompose.ui.screens.tutorial.navdatapass.NavDataPassOneScreen
import org.imaginativeworld.whynotcompose.ui.screens.tutorial.navdatapass.NavDataPassThreeScreen
import org.imaginativeworld.whynotcompose.ui.screens.tutorial.navdatapass.NavDataPassTwoScreen
import org.imaginativeworld.whynotcompose.ui.screens.tutorial.onesignalandbroadcast.OneSignalAndBroadcastScreen
import org.imaginativeworld.whynotcompose.ui.screens.tutorial.permission.PermissionScreen
import org.imaginativeworld.whynotcompose.ui.screens.tutorial.reactivemodel.ReactiveModelScreen
import org.imaginativeworld.whynotcompose.ui.screens.tutorial.reactivemodel.ReactiveModelViewModel
Expand Down Expand Up @@ -232,7 +231,6 @@ sealed class TutorialsScreen(val route: String) {
data object TutorialPermission : TutorialsScreen("tutorial/permission")
data object TutorialDataFetchAndPaging : TutorialsScreen("tutorial/data-fetch-and-paging")
data object TutorialTicTacToe : TutorialsScreen("tutorial/tic-tac-toe")
data object TutorialOneSignalAndBroadcast : TutorialsScreen("tutorial/onesignal-and-broadcast")
data object TutorialExoPlayer : TutorialsScreen("tutorial/exoplayer")
data object TutorialCMS : TutorialsScreen("tutorial/cms")
data object TutorialDeepLink : TutorialsScreen("tutorial/deep-link")
Expand Down Expand Up @@ -949,14 +947,6 @@ private fun NavGraphBuilder.addTutorialIndexScreen(
)
}

composable(TutorialsScreen.TutorialOneSignalAndBroadcast.route) {
OneSignalAndBroadcastScreen(
goBack = {
navController.popBackStackOrIgnore()
}
)
}

composable(TutorialsScreen.TutorialExoPlayer.route) {
ExoPlayerScreen(
goBack = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,6 @@ data class Tutorial(
route = TutorialsScreen.TutorialTicTacToe,
level = TutorialLevel.Advanced
),
Tutorial(
name = "OneSignal and Broadcast",
description = "Send notification with data using `OneSignal`, then send broadcast when a new notification comes. Finally, receive the broadcast and data from Compose UI.",
route = TutorialsScreen.TutorialOneSignalAndBroadcast,
level = TutorialLevel.Intermediate
),
Tutorial(
name = "ExoPlayer",
description = "Example usage of `ExoPlayer` with Compose.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,15 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.onesignal.OneSignal
import org.imaginativeworld.whynotcompose.base.extensions.toast
import org.imaginativeworld.whynotcompose.base.utils.Constants
import org.imaginativeworld.whynotcompose.common.compose.compositions.AppComponent
import org.imaginativeworld.whynotcompose.common.compose.theme.AppTheme
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber

// ⚠️ WARNING ⚠️
// This tutorial is deprecated. Because OneSignal removed the `postNotification` method.
// Details: https://github.com/OneSignal/OneSignal-Unity-SDK/issues/585

@Composable
fun OneSignalAndBroadcastScreen(
Expand All @@ -77,7 +78,7 @@ fun OneSignalAndBroadcastScreen(

DisposableEffect(context) {
/**
* We will receive the broadcast data here. See [MyNotificationWillShowInForegroundHandler]
* We will receive the broadcast data here. See [MyNotificationLifecycleListener]
* for how to receive data and broadcast data when a new OneSignal notification comes.
*/
val broadcast = object : BroadcastReceiver() {
Expand Down Expand Up @@ -106,9 +107,9 @@ fun OneSignalAndBroadcastScreen(
try {
counter++

sendNewNotification(counter.toString()) { errorMessage ->
showError = errorMessage
}
// sendNewNotification(counter.toString()) { errorMessage ->
// showError = errorMessage
// }
} catch (e: JSONException) {
e.printStackTrace()

Expand Down Expand Up @@ -140,42 +141,42 @@ fun OneSignalAndBroadcastScreen(
/**
* Send a new OneSignal notification to the current app user with given [value].
*/
private fun sendNewNotification(value: String, onError: (String) -> Unit) {
if (OneSignal.getDeviceState() != null && OneSignal.getDeviceState()!!.isSubscribed) {
// This is the current device OneSignal userId.
val userId = OneSignal.getDeviceState()!!.userId

OneSignal.postNotification(
"""
{
"contents": {
"en": "Current value is $value"
},
"data": {
"value": "$value"
},
"include_player_ids": [
"$userId"
]
}
""".trimIndent(),
object : OneSignal.PostNotificationResponseHandler {
override fun onSuccess(response: JSONObject?) {
Timber.i("postNotification Success: " + response.toString())
}

override fun onFailure(response: JSONObject?) {
Timber.e("postNotification Failure: " + response.toString())
}
}
)
} else {
onError(
"OneSignal is not initialized yet or the user is not subscribed! " +
"Another reason could be notification permission is not allowed."
)
}
}
// private fun sendNewNotification(value: String, onError: (String) -> Unit) {
// if (OneSignal.getDeviceState() != null && OneSignal.getDeviceState()!!.isSubscribed) {
// // This is the current device OneSignal userId.
// val userId = OneSignal.getDeviceState()!!.userId
//
// OneSignal.postNotification(
// """
// {
// "contents": {
// "en": "Current value is $value"
// },
// "data": {
// "value": "$value"
// },
// "include_player_ids": [
// "$userId"
// ]
// }
// """.trimIndent(),
// object : OneSignal.PostNotificationResponseHandler {
// override fun onSuccess(response: JSONObject?) {
// Timber.i("postNotification Success: " + response.toString())
// }
//
// override fun onFailure(response: JSONObject?) {
// Timber.e("postNotification Failure: " + response.toString())
// }
// }
// )
// } else {
// onError(
// "OneSignal is not initialized yet or the user is not subscribed! " +
// "Another reason could be notification permission is not allowed."
// )
// }
// }

@PreviewLightDark
@Composable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import org.imaginativeworld.whynotcompose.common.compose.compositions.AppComponent
import org.imaginativeworld.whynotcompose.common.compose.theme.AppTheme
import org.imaginativeworld.whynotcompose.models.MapPlace
import org.imaginativeworld.whynotcompose.repositories.MapPlaceRepo
Expand Down Expand Up @@ -86,24 +87,19 @@ fun MapViewDetailsScreenSkeleton(
Modifier
.navigationBarsPadding()
.imePadding()
.statusBarsPadding()
.statusBarsPadding(),
topBar = {
AppComponent.Header(
item.name,
goBack = goBack
)
}
) { innerPadding ->
Column(
Modifier
.padding(innerPadding)
.fillMaxSize()
) {
TopAppBar(
title = { Text(item.name) },
navigationIcon = {
IconButton(onClick = {
goBack()
}) {
Icon(Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = null)
}
}
)

Row(
Modifier
.fillMaxWidth()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ fun MapScreen(
viewModel.loadMapPlaces()
},
mapView = { modifier ->

GoogleMap(
modifier = modifier,
cameraPositionState = cameraPositionState,
Expand Down Expand Up @@ -267,7 +266,6 @@ fun MapSkeleton(
mapView(
Modifier
.padding(innerPadding)
.padding(top = 56.dp)
.fillMaxSize()
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,33 +28,22 @@ package org.imaginativeworld.whynotcompose.utils.onesignal

import android.app.Application
import android.content.Intent
import com.onesignal.OSNotificationOpenedResult
import com.onesignal.OneSignal
import com.onesignal.notifications.INotificationClickEvent
import com.onesignal.notifications.INotificationClickListener
import org.imaginativeworld.whynotcompose.base.utils.Constants
import org.imaginativeworld.whynotcompose.ui.screens.MainActivity
import timber.log.Timber

// This fires when a notification is opened by tapping on it.
class MyNotificationOpenedHandler(
class MyNotificationClickListener(
private val application: Application
) : OneSignal.OSNotificationOpenedHandler {
override fun notificationOpened(result: OSNotificationOpenedResult?) {
) : INotificationClickListener {
override fun onClick(event: INotificationClickEvent) {
Timber.d("notificationOpened")

Timber.i("result.getNotification().getRawPayload(): %s", result!!.notification.rawPayload)

// OSNotificationAction.ActionType actionType = result.action.type;
// JSONObject data = result.notification.payload.additionalData;
// String customKey;

// if (data != null) {
// customKey = data.optString("customkey", null);
// if (customKey != null)
// Timber.i("OneSignalExample: customkey set with value: %s", customKey);
// }
//
// if (actionType == OSNotificationAction.ActionType.ActionTaken)
// Timber.i("OneSignalExample: Button pressed with id: %s", result.action.actionID);
Timber.i(
"result.getNotification().getRawPayload(): %s",
event.notification.rawPayload
)

// Pending intent
val intent = Intent(application.applicationContext, MainActivity::class.java)
Expand All @@ -64,7 +53,8 @@ class MyNotificationOpenedHandler(
Constants.INTENT_EXTRA_TARGET_VAL_NOTIFICATIONS
)

intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_NEW_TASK
intent.flags =
Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_NEW_TASK
application.startActivity(intent)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,26 @@ package org.imaginativeworld.whynotcompose.utils.onesignal
import android.app.Application
import android.content.Intent
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.onesignal.OSNotificationReceivedEvent
import com.onesignal.OneSignal
import com.onesignal.notifications.INotificationLifecycleListener
import com.onesignal.notifications.INotificationWillDisplayEvent
import org.imaginativeworld.whynotcompose.base.utils.Constants
import org.json.JSONException
import timber.log.Timber

// Runs before displaying a notification while the app is in focus. Use this handler to decide if the notification should show or not.
class MyNotificationWillShowInForegroundHandler(
class MyNotificationLifecycleListener(
private val application: Application
) : OneSignal.OSNotificationWillShowInForegroundHandler {
override fun notificationWillShowInForeground(notificationReceivedEvent: OSNotificationReceivedEvent?) {
) : INotificationLifecycleListener {
override fun onWillDisplay(event: INotificationWillDisplayEvent) {
Timber.v(
"INotificationLifecycleListener.onWillDisplay fired" +
" with event: " + event
)
val notification = event.notification
// Get custom additional data you sent with the notification
val data = notificationReceivedEvent?.notification?.additionalData
val data = notification.additionalData

Timber.i("Additional Data: $data")

// Complete with a notification means it will show
notificationReceivedEvent?.complete(notificationReceivedEvent.notification)

// --------------------------------------------------------------------
// Send broadcast
// --------------------------------------------------------------------
Expand Down
Loading

0 comments on commit db44f8b

Please sign in to comment.