Skip to content

Commit

Permalink
Use separate channels and IDs for foreground notifications and alerts
Browse files Browse the repository at this point in the history
This allows users to individually disable the types of notifications
they don't want. Using separate notification IDs also prevents Android
from dismissing the wrong notification when the service leaves
foreground mode.

Signed-off-by: Andrew Gunnerson <[email protected]>
  • Loading branch information
chenxiaolong committed May 25, 2024
1 parent f0ba7a3 commit 97389d4
Show file tree
Hide file tree
Showing 15 changed files with 37 additions and 39 deletions.
8 changes: 4 additions & 4 deletions app/src/main/java/com/github/tmo1/sms_ie/ExportWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class ExportWorker(appContext: Context, workerParams: WorkerParameters) :
// many binder transactions in the background, which can happen when exporting many
// messages. Running the service in the foreground prevents the app from being killed.
// https://android.googlesource.com/platform/frameworks/base.git/+/71d75c09b9a06732a6edb4d1488d2aa3eb779e14%5E%21/
val foregroundNotification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
val foregroundNotification = NotificationCompat.Builder(applicationContext, CHANNEL_ID_PERSISTENT)
.setSmallIcon(R.mipmap.ic_launcher_foreground)
.setContentTitle(context.getString(R.string.scheduled_export_executing))
.setOngoing(true).build()
Expand All @@ -78,7 +78,7 @@ class ExportWorker(appContext: Context, workerParams: WorkerParameters) :
0
}
try {
setForeground(ForegroundInfo(0, foregroundNotification, foregroundFlags))
setForeground(ForegroundInfo(NOTIFICATION_ID_PERSISTENT, foregroundNotification, foregroundFlags))
} catch (e: Exception) {
// If the user didn't allow the disabling of battery optimizations, then Android 12+'s
// restrictions for starting a foreground service from the background will prevent this
Expand Down Expand Up @@ -156,15 +156,15 @@ class ExportWorker(appContext: Context, workerParams: WorkerParameters) :
contacts
) else context.getString(R.string.scheduled_export_failure)
// https://developer.android.com/training/notify-user/build-notification#builder
val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID_ALERTS)
//.setSmallIcon(R.drawable.ic_launcher_foreground)
.setSmallIcon(R.drawable.ic_scheduled_export_done)
.setContentTitle(context.getString(R.string.scheduled_export_executed))
.setContentText(notification).setPriority(NotificationCompat.PRIORITY_DEFAULT)
// https://developer.android.com/training/notify-user/build-notification#notify
with(NotificationManagerCompat.from(applicationContext)) {
// notificationId is a unique int for each notification that you must define
{ notify(0, builder.build()) }
{ notify(NOTIFICATION_ID_ALERT, builder.build()) }
}
}
}
Expand Down
38 changes: 29 additions & 9 deletions app/src/main/java/com/github/tmo1/sms_ie/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ const val IMPORT_CONTACTS = 6
const val BECOME_DEFAULT_SMS_APP = 100
const val PERMISSIONS_REQUEST = 1
const val LOG_TAG = "SMSIE"
const val CHANNEL_ID = "MYCHANNEL"
const val CHANNEL_ID_PERSISTENT = "PERSISTENT"
const val CHANNEL_ID_ALERTS = "ALERTS"
const val NOTIFICATION_ID_PERSISTENT = 0
const val NOTIFICATION_ID_ALERT = 1

// PduHeaders are referenced here https://developer.android.com/reference/android/provider/Telephony.Mms.Addr#TYPE
// and defined here https://android.googlesource.com/platform/frameworks/opt/mms/+/4bfcd8501f09763c10255442c2b48fad0c796baa/src/java/com/google/android/mms/pdu/PduHeaders.java
Expand Down Expand Up @@ -172,16 +175,33 @@ class MainActivity : AppCompatActivity(), ConfirmWipeFragment.NoticeDialogListen
// https://developer.android.com/training/notify-user/channels
// https://developer.android.com/training/notify-user/build-notification#Priority
if (SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
mChannel.description = descriptionText
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)

notificationManager.createNotificationChannel(
NotificationChannel(
CHANNEL_ID_PERSISTENT,
getString(R.string.persistent_channel_name),
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = getString(R.string.persistent_channel_description)
}
)

notificationManager.createNotificationChannel(
NotificationChannel(
CHANNEL_ID_ALERTS,
getString(R.string.alerts_channel_name),
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = getString(R.string.alerts_channel_description)
}
)

// Remove legacy notification channels to accommodate upgrades
notificationManager.deleteNotificationChannel("MYCHANNEL")
}
}

Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-b+de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@
<string name="not_jsonarray_message">Die Datei scheint kein gültiges JSON-Array zu enthalten.</string>
<string name="settings">Einstellungen</string>
<string name="include_binary_data">Einschließlich binärer MMS-Daten</string>
<string name="channel_name">Benachrichtigungskanal</string>
<string name="channel_description">Benachrichtigungskanal</string>
<string name="scheduled_export_executed">Geplanter Export ausgeführt</string>
<string name="scheduled_export_success">%1$d SMS, %2$d MMS , %3$d Anruf(e) und %4$d Kontakt(e) exportiert.</string>
<string name="scheduled_export_failure">Export fehlgeschlagen — siehe Logcat für weitere Details.</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-b+fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@
<string name="call_logs_read_write_permissions_required">L\'importation de l\'historique des appels nécessite l\'autorisation de lire et écrire l\'historique des appels.</string>
<string name="contacts_read_permission_required">L\'exportation des contacts nécessite l\'autorisation de lire les contacts.</string>
<string name="contacts_write_permissions_required">L\'importation des contacts nécessite l\'autorisation d\'écrire les contacts.</string>
<string name="channel_name">canal_de_notification</string>
<string name="channel_description">Canal de Notification</string>
<string name="scheduled_export_executed">Exportation planifiée exécutée</string>
<string name="scheduled_export_success">%1$d SMS(s), %2$d MMS(s), %3$d appel(s), et %4$d contact(s) exporté(s).</string>
<string name="wipe_messages">Effacer les messages</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
<string name="contacts_read_permission_required">Para exportar los contactos se requiere el permiso de lectura de los contactos.</string>
<string name="contacts_write_permissions_required">Para importar los contactos se requiere permiso para escribir en los contactos.</string>
<string name="not_jsonarray_message">El archivo no parece contener un JSONArray válido.</string>
<string name="channel_description">Canal de notificaciones</string>
<string name="scheduled_export_executed">Exportación programada ejecutada</string>
<string name="scheduled_export_success">%1$d SMS(es), %2$d MMS(es), %3$d llamadas y %4$d contactos exportados.</string>
<string name="wipe_messages">Borrar mensajes</string>
Expand Down Expand Up @@ -49,7 +48,6 @@
<string name="call_logs_read_write_permissions_required">Para importar los registros de llamadas se requiere permisos para leer y escribir en los registros de llamadas.</string>
<string name="settings">Ajustes</string>
<string name="include_binary_data">Incluir los datos binarios de los MMS</string>
<string name="channel_name">canal_de_notificaciones</string>
<string name="scheduled_export_failure">Exportación incorrecta — consulte el logcat para obtener más detalles.</string>
<string name="dialog_confirm_wipe">Advertencia: ¿Borrar todos los mensajes de este dispositivo de forma permanente, sin que se pueda deshacerlo\?</string>
<string name="wiping_mms_messages">Borrando los mensajes MMS …</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-fa/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
<string name="call_logs_read_write_permissions_required">درون‌برد گزارش‌های تماس برای خواندن و نوشتن گزارش‌های تماس به مجوز نیاز دارد.</string>
<string name="contacts_read_permission_required">برون‌برد مخاطبین برای خواندن مخاطبین به مجوز نیاز دارد.</string>
<string name="settings">تنظیمات</string>
<string name="channel_name">اطلاع‌رسانی_کانال</string>
<string name="channel_description">کانال اطلاع‌رسانی</string>
<string name="scheduled_export_executed">برون‌برد برنامه ریزی شده اجرا شد</string>
<string name="scheduled_export_success">%1$d پیامک ، %2$d پیام چندرسانه‌ای، %3$d تماس و %4$d مخاطب برون‌برد شد.</string>
<string name="scheduled_export_failure">برون‌برد ناموفق بود — برای جزئیات بیشتر به گزارش مراجعه کنید.</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-it/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@
<string name="issue_tracker">Segnalazione problemi:</string>
<string name="about">Informazioni</string>
<string name="export_contacts">Esporta contatti</string>
<string name="channel_name">notification_channel</string>
<string name="channel_description">Canale notifiche</string>
<string name="scheduled_export_executing">Esecuzione esportazione pianificata</string>
<string name="copying_mms_binary_data">Copia dati binari MMS ...</string>
<string name="importing_messages">Importazione messaggi...</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-iw/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
<string name="call_logs_permissions_required">ייצוא יומני שיחות דורש הרשאה לקרוא יומני שיחות ואנשי קשר.</string>
<string name="call_logs_read_write_permissions_required">ייבוא יומני שיחות דורש הרשאה לקרוא ולכתוב יומני שיחות.</string>
<string name="include_binary_data">כלול נתוני MMS בינאריים (מקודדים)</string>
<string name="channel_description">notification Channel</string>
<string name="scheduled_export_executed">ייצוא מתוזמן בוצע</string>
<string name="channel_name">Notification_channel</string>
<string name="scheduled_export_success">%1$d הודעות סמס, %2$d mms, %3$d שיחות ו-%4$d אנשי קשר יוצאו.</string>
<string name="scheduled_export_failure">הייצוא לא הצליח - ראה logcat לפרטים נוספים.</string>
<string name="dialog_confirm_wipe">אזהרה: למחוק את כל ההודעות מהמכשיר הזה לצמיתות, מבלי שתוכל לבטל זאת\?</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-nb-rNO/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
<string name="call_logs_permissions_required">Eksportering av anropslogger krever tilgang til å lese anropslogg og kontaktliste.</string>
<string name="sms_permissions_required">Eksportering av meldinger krever tilgang til å lese SMS-er og kontaktliste.</string>
<string name="default_sms_app_requirement">Programmet må være forvalgt meldingsprogram for å importere eller slette meldinger.</string>
<string name="channel_name">Merknadskanal</string>
<string name="scheduled_export_success">%1$d SMS(-er), %2$d MMS(-er), og %3$d anrop eksportert.</string>
<string name="wipe_messages">Tøm meldinger</string>
<string name="homepage">Hjemmeside:</string>
Expand Down Expand Up @@ -43,7 +42,6 @@
<string name="settings">Innstillinger</string>
<string name="scheduled_export_executed">Planlagt eksport kjørt</string>
<string name="include_binary_data">Inkluder (kodet) binær MMS-data</string>
<string name="channel_description">Merknadskanal</string>
<string name="cancel">Avbryt</string>
<string name="not_jsonarray_message">Filen ser ikke ut til å være et gyldig JSON-array.</string>
<string name="wipe">Tøm</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-pl/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
<string name="not_jsonarray_message">Wydaje się, że plik nie zawiera poprawnej tablicy JSONArray.</string>
<string name="settings">Ustawienia</string>
<string name="include_binary_data">Dołącz binarne dane MMS</string>
<string name="channel_description">Kanał powiadomień</string>
<string name="scheduled_export_executed">Zaplanowany eksport wykonany</string>
<string name="scheduled_export_success">Wyeksportowano %1$d SMSów, %2$d MMSów, %3$d połączeń i %4$d kontaktów.</string>
<string name="wipe_messages">Usuń wiadomości</string>
Expand All @@ -60,7 +59,6 @@
\nPrawa autorskie © 2021–24
\n
\nWydane na licencji GNU GPLv3</string>
<string name="channel_name">kanał_powiadomień</string>
<string name="call_log_export_progress">Wyeksportowano %1$d z %2$d połączeń</string>
<string name="copying_mms_binary_data">Kopiowanie binarnych danych MMS...</string>
<string name="importing_messages">Importowanie wiadomości...</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-pt/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,11 @@
<string name="wiping_mms_messages">A apagar mensagens MMS …</string>
<string name="documentation">Documentação:</string>
<string name="homepage">Homepage:</string>
<string name="channel_name">canal_de_notificação</string>
<string name="call_log_import_progress">%1$d chamada(s) importadas</string>
<string name="issue_tracker">Reportar de erros:</string>
<string name="app_name">Importar / Exportar SMS</string>
<string name="about">Sobre</string>
<string name="call_log_export_progress">%1$d de %2$d chamada(s) exportadas</string>
<string name="channel_description">Canal de Notificação</string>
<string name="scheduled_export_failure">Exportação sem sucesso — ver logcat para mais detalhes.</string>
<string name="scheduled_export_executed">Exportação agendada executada</string>
<string name="app_about_text">SMS Import / Export
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-tr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@
<string name="not_jsonarray_message">Dosya geçerli bir JSONArray içermiyor gibi görünüyor.</string>
<string name="settings">Ayarlar</string>
<string name="include_binary_data">İkili MMS verilerini dahil et</string>
<string name="channel_name">bildirim_kanali</string>
<string name="channel_description">Bildirim Kanalı</string>
<string name="scheduled_export_executed">Planlanan dışa aktarma gerçekleştirildi</string>
<string name="scheduled_export_success">%1$d SMS, %2$d MMS, %3$d arama ve %4$d kisi dışa aktarıldı.</string>
<string name="scheduled_export_failure">Dışa aktarma başarısız — daha fazla ayrıntı için logcat\'e bakın.</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-vi/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,10 @@
<string name="default_sms_app_dialog_title">Ứng dụng SMS mặc định</string>
<string name="message_import_api_23_requirement">Chỉ có thể nhập tin nhắn trên Android Marshmallow / 6.0 (API cấp 23) trở lên.</string>
<string name="include_binary_data">Bao gồm dữ liệu MMS nhị phân</string>
<string name="channel_description">Kênh thông báo</string>
<string name="dialog_confirm_wipe">Cảnh báo: Xóa vĩnh viễn tất cả tin nhắn khỏi thiết bị này mà không thể hoàn tác?</string>
<string name="wipe">Xóa</string>
<string name="cancel">Hủy</string>
<string name="wipe_cancelled">Đã hủy xóa</string>
<string name="channel_name">kênh_thông báo</string>
<string name="call_logs_permissions_required">Việc xuất nhật ký cuộc gọi cần có quyền đọc Nhật ký cuộc gọi và Danh bạ.</string>
<string name="scheduled_export_executing">Thực hiện xuất khẩu theo lịch trình</string>
<string name="scheduled_export_executed">Đã thực hiện xuất theo lịch trình</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-zh-rCN/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,9 @@
<string name="call_logs_read_write_permissions_required">导入通话记录的功能,需要读取、写入通话记录的权限。</string>
<string name="not_jsonarray_message">在文件中没找到有效的 JSONArray。</string>
<string name="dialog_confirm_wipe">警告:要无法撤销地永久擦除此设备上的所有消息吗?</string>
<string name="channel_description">通知通道</string>
<string name="export_contacts_results">导出了 %1$d 位联系人
\n耗费时间:%2$s。</string>
<string name="contacts_read_permission_required">导出联系人需要读取联系人权限。</string>
<string name="channel_name">notification_channel</string>
<string name="export_contacts">导出联系人</string>
<string name="import_contacts">导入联系人</string>
<string name="contacts_export_progress">导出了 %2$d 位联系人中的 %1$d 位</string>
Expand Down
6 changes: 4 additions & 2 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@
<string name="not_jsonarray_message">The file does not seem to contain a valid JSONArray.</string>
<string name="settings">Settings</string>
<string name="include_binary_data">Include binary MMS data</string>
<string name="channel_name">notification_channel</string>
<string name="channel_description">Notification Channel</string>
<string name="persistent_channel_name">Background services</string>
<string name="persistent_channel_description">Persistent notification for background scheduled exports</string>
<string name="alerts_channel_name">Scheduled export alerts</string>
<string name="alerts_channel_description">Success/failure alerts when scheduled exports complete</string>
<string name="scheduled_export_executing">Scheduled export executing</string>
<string name="scheduled_export_executed">Scheduled export executed</string>
<string name="scheduled_export_success">%1$d SMS(s), %2$d MMS(s), %3$d calls, and %4$d contacts exported.</string>
Expand Down

0 comments on commit 97389d4

Please sign in to comment.