simplify android impl

pull/340/head
Lucas Nogueira 2 years ago
parent 038f6d32fc
commit 5542fbae4e
No known key found for this signature in database
GPG Key ID: 7C32FCA95C8C95D7

@ -138,14 +138,6 @@ class ChannelManager(private var context: Context) {
0xFFFFFF and notificationChannel.lightColor 0xFFFFFF and notificationChannel.lightColor
) )
) )
Logger.debug(
Logger.tags("NotificationChannel"),
"visibility " + notificationChannel.lockscreenVisibility
)
Logger.debug(
Logger.tags("NotificationChannel"),
"importance " + notificationChannel.importance
)
channels.put(channel) channels.put(channel)
} }
val result = JSObject() val result = JSObject()

@ -4,13 +4,10 @@ import android.content.ContentResolver
import android.content.Context import android.content.Context
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import app.tauri.Logger
import app.tauri.plugin.Invoke
import app.tauri.plugin.JSArray import app.tauri.plugin.JSArray
import app.tauri.plugin.JSObject import app.tauri.plugin.JSObject
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
import java.text.ParseException
class Notification { class Notification {
var title: String? = null var title: String? = null
@ -170,15 +167,6 @@ class Notification {
return result return result
} }
fun setExtraFromString(extraFromString: String) {
try {
val jsonObject = JSONObject(extraFromString)
extra = JSObject.fromJSONObject(jsonObject)
} catch (e: JSONException) {
Logger.error(Logger.tags("Notification"), "Cannot rebuild extra data", e)
}
}
companion object { companion object {
fun fromJson(jsonNotification: JSONObject): Notification { fun fromJson(jsonNotification: JSONObject): Notification {
val notification: JSObject = try { val notification: JSObject = try {
@ -229,26 +217,6 @@ class Notification {
return notification return notification
} }
fun getNotificationPendingList(invoke: Invoke): List<Int>? {
var notifications: List<JSONObject>? = null
try {
notifications = invoke.getArray("notifications", JSArray()).toList()
} catch (_: JSONException) {
}
if (notifications.isNullOrEmpty()) {
invoke.reject("Must provide notifications array as notifications option")
return null
}
val notificationsList: MutableList<Int> = ArrayList(notifications.size)
for (notificationToCancel in notifications) {
try {
notificationsList.add(notificationToCancel.getInt("id"))
} catch (_: JSONException) {
}
}
return notificationsList
}
fun buildNotificationPendingList(notifications: List<Notification>): JSObject { fun buildNotificationPendingList(notifications: List<Notification>): JSObject {
val result = JSObject() val result = JSObject()
val jsArray = JSArray() val jsArray = JSArray()

@ -98,21 +98,20 @@ class NotificationPlugin(private val activity: Activity): Plugin(activity) {
notificationStorage.appendNotifications(notifications) notificationStorage.appendNotifications(notifications)
val result = JSObject() val result = JSObject()
val jsArray = JSArray() result.put("notifications", ids)
for (id in ids) {
try {
val notification = JSObject().put("id", id)
jsArray.put(notification)
} catch (_: Exception) {
}
}
result.put("notifications", jsArray)
invoke.resolve(result) invoke.resolve(result)
} }
@Command @Command
void cancel(invoke: Invoke) { fun cancel(invoke: Invoke) {
manager.cancel(invoke) val notifications: List<Int> = invoke.getArray("notifications", JSArray()).toList()
if (notifications.isEmpty()) {
invoke.reject("Must provide notifications array as notifications option")
return
}
manager.cancel(notifications)
invoke.resolve()
} }
@Command @Command

@ -21,15 +21,12 @@ import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import androidx.core.app.RemoteInput import androidx.core.app.RemoteInput
import app.tauri.Logger import app.tauri.Logger
import app.tauri.plugin.Invoke
import app.tauri.plugin.JSObject import app.tauri.plugin.JSObject
import org.json.JSONArray
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Date import java.util.Date
// Action constants // Action constants
const val NOTIFICATION_INTENT_KEY = "NotificationId" const val NOTIFICATION_INTENT_KEY = "NotificationId"
const val NOTIFICATION_OBJ_INTENT_KEY = "LocalNotficationObject" const val NOTIFICATION_OBJ_INTENT_KEY = "LocalNotficationObject"
@ -246,7 +243,7 @@ class TauriNotificationManager(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = flags or PendingIntent.FLAG_MUTABLE flags = flags or PendingIntent.FLAG_MUTABLE
} }
val pendingIntent = PendingIntent.getActivity(context, notification.id ?: 0, intent, flags) val pendingIntent = PendingIntent.getActivity(context, notification.id, intent, flags)
mBuilder.setContentIntent(pendingIntent) mBuilder.setContentIntent(pendingIntent)
// Build action types // Build action types
@ -258,7 +255,7 @@ class TauriNotificationManager(
val actionIntent = buildIntent(notification, notificationAction!!.id) val actionIntent = buildIntent(notification, notificationAction!!.id)
val actionPendingIntent = PendingIntent.getActivity( val actionPendingIntent = PendingIntent.getActivity(
context, context,
(notification.id ?: 0) + notificationAction.id.hashCode(), (notification.id) + notificationAction.id.hashCode(),
actionIntent, actionIntent,
flags flags
) )
@ -295,7 +292,7 @@ class TauriNotificationManager(
flags = PendingIntent.FLAG_MUTABLE flags = PendingIntent.FLAG_MUTABLE
} }
val deleteIntent = val deleteIntent =
PendingIntent.getBroadcast(context, notification.id ?: 0, dissmissIntent, flags) PendingIntent.getBroadcast(context, notification.id, dissmissIntent, flags)
mBuilder.setDeleteIntent(deleteIntent) mBuilder.setDeleteIntent(deleteIntent)
} }
@ -317,6 +314,7 @@ class TauriNotificationManager(
* on a certain date "shape" (such as every first of the month) * on a certain date "shape" (such as every first of the month)
*/ */
// TODO support different AlarmManager.RTC modes depending on priority // TODO support different AlarmManager.RTC modes depending on priority
@SuppressLint("SimpleDateFormat")
private fun triggerScheduledNotification(notification: android.app.Notification, request: Notification) { private fun triggerScheduledNotification(notification: android.app.Notification, request: Notification) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val schedule = request.schedule val schedule = request.schedule
@ -331,7 +329,7 @@ class TauriNotificationManager(
flags = flags or PendingIntent.FLAG_MUTABLE flags = flags or PendingIntent.FLAG_MUTABLE
} }
var pendingIntent = var pendingIntent =
PendingIntent.getBroadcast(context, request.id ?: 0, notificationIntent, flags) PendingIntent.getBroadcast(context, request.id, notificationIntent, flags)
when (val scheduleKind = schedule?.kind) { when (val scheduleKind = schedule?.kind) {
is ScheduleKind.At -> { is ScheduleKind.At -> {
@ -351,7 +349,7 @@ class TauriNotificationManager(
val trigger = scheduleKind.interval.nextTrigger(Date()) val trigger = scheduleKind.interval.nextTrigger(Date())
notificationIntent.putExtra(TimedNotificationPublisher.CRON_KEY, scheduleKind.interval.toMatchString()) notificationIntent.putExtra(TimedNotificationPublisher.CRON_KEY, scheduleKind.interval.toMatchString())
pendingIntent = pendingIntent =
PendingIntent.getBroadcast(context, request.id ?: 0, notificationIntent, flags) PendingIntent.getBroadcast(context, request.id, notificationIntent, flags)
setExactIfPossible(alarmManager, schedule, trigger, pendingIntent) setExactIfPossible(alarmManager, schedule, trigger, pendingIntent)
val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
Logger.debug( Logger.debug(
@ -376,13 +374,13 @@ class TauriNotificationManager(
pendingIntent: PendingIntent pendingIntent: PendingIntent
) { ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !alarmManager.canScheduleExactAlarms()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && schedule.whileIdle == true) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && schedule.whileIdle) {
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent) alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent)
} else { } else {
alarmManager[AlarmManager.RTC, trigger] = pendingIntent alarmManager[AlarmManager.RTC, trigger] = pendingIntent
} }
} else { } else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && schedule.whileIdle == true) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && schedule.whileIdle) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent) alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pendingIntent)
} else { } else {
alarmManager.setExact(AlarmManager.RTC, trigger, pendingIntent) alarmManager.setExact(AlarmManager.RTC, trigger, pendingIntent)
@ -390,16 +388,12 @@ class TauriNotificationManager(
} }
} }
fun cancel(invoke: Invoke) { fun cancel(notifications: List<Int>) {
val notificationsToCancel = Notification.getNotificationPendingList(invoke) for (id in notifications) {
if (notificationsToCancel != null) { dismissVisibleNotification(id)
for (id in notificationsToCancel) { cancelTimerForNotification(id)
dismissVisibleNotification(id) storage.deleteNotification(id.toString())
cancelTimerForNotification(id)
storage.deleteNotification(id.toString())
}
} }
invoke.resolve()
} }
private fun cancelTimerForNotification(notificationId: Int) { private fun cancelTimerForNotification(notificationId: Int) {
@ -511,7 +505,7 @@ class TimedNotificationPublisher : BroadcastReceiver() {
return intent.getParcelableExtra(string) return intent.getParcelableExtra(string)
} }
@SuppressLint("MissingPermission") @SuppressLint("MissingPermission", "SimpleDateFormat")
private fun rescheduleNotificationIfNeeded(context: Context, intent: Intent, id: Int): Boolean { private fun rescheduleNotificationIfNeeded(context: Context, intent: Intent, id: Int): Boolean {
val dateString = intent.getStringExtra(CRON_KEY) val dateString = intent.getStringExtra(CRON_KEY)
if (dateString != null) { if (dateString != null) {

@ -83,21 +83,16 @@ class NotificationPlugin: Plugin {
invoke.reject("`notifications` array is required") invoke.reject("`notifications` array is required")
return return
} }
var ids = [String]() var ids = [Int]()
for notification in notifications { for notification in notifications {
let request = try showNotification(invoke: invoke, notification: notification) let request = try showNotification(invoke: invoke, notification: notification)
// TODO self.notificationHandler.notificationsMap[request.identifier] = notification // TODO self.notificationHandler.notificationsMap[request.identifier] = notification
ids.append(request.identifier) ids.append(Int(request.identifier) ?? -1)
} }
let ret = ids.map({ (id) -> JSObject in
return [
"id": Int(id) ?? -1
]
})
invoke.resolve([ invoke.resolve([
"notifications": ret "notifications": ids
]) ])
} }
@ -131,23 +126,18 @@ class NotificationPlugin: Plugin {
} }
@objc func cancel(_ invoke: Invoke) { @objc func cancel(_ invoke: Invoke) {
guard let notifications = invoke.getArray("notifications", JSObject.self), guard let notifications = invoke.getArray("notifications", NSNumber.self),
notifications.count > 0 notifications.count > 0
else { else {
invoke.reject("`notifications` input is required") invoke.reject("`notifications` input is required")
return return
} }
let ids = notifications.map({ (value: JSObject) -> String in UNUserNotificationCenter.current().removePendingNotificationRequests(
if let idString = value["id"] as? String { withIdentifiers: notifications.map({ (id) -> String in
return idString return id.stringValue
} else if let idNum = value["id"] as? NSNumber { })
return idNum.stringValue )
}
return ""
})
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ids)
invoke.resolve() invoke.resolve()
} }

@ -110,17 +110,7 @@ impl<R: Runtime> Notification<R> {
/// Cancel pending notifications. /// Cancel pending notifications.
pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> { pub fn cancel(&self, notifications: Vec<i32>) -> crate::Result<()> {
let mut args = HashMap::new(); let mut args = HashMap::new();
args.insert( args.insert("notifications", notifications);
"notifications",
notifications
.into_iter()
.map(|id| {
let mut notification = HashMap::new();
notification.insert("id", id);
notification
})
.collect::<Vec<HashMap<&str, i32>>>(),
);
self.0.run_mobile_plugin("cancel", args).map_err(Into::into) self.0.run_mobile_plugin("cancel", args).map_err(Into::into)
} }

Loading…
Cancel
Save