#android #android-studio #kotlin
#Android #android-studio #kotlin
Вопрос:
i want to show push notification in kotlin at 7 AM amp; 16PM in here every 24Hours everyday. i make 2 broadcast receiver amp; 2 declare time inside oncreate, but sometimes push notification not show, i dont know if receiver blocked by miui saver
below my code AlarmBroadcastreceiver (for show 7 AM):
class AlarmBroadcastReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
showNotification(context)
}
internal fun showNotification(context: Context) {
val CHANNEL_ID = "1"// The id of the channel.
val name = context.getResources().getString(R.string.app_name)// The user-visible name of the channel.
val mBuilder: NotificationCompat.Builder
val intent = Intent()
val manufacturer = android.os.Build.MANUFACTURER
when(manufacturer) {
"xiaomi" ->
intent.component =
ComponentName(
"com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"
)
"oppo" ->
intent.component =
ComponentName(
"com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity"
)
"vivo" ->
intent.component =
ComponentName(
"com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity"
)
"samsung" ->
intent.component =
ComponentName(
"com.samsung.android.lool",
"com.samsung.android.sm.ui.battery.BatteryActivity"
)
"asus" ->
intent.component =
ComponentName(
"com.asus.mobilemanager",
"com.asus.mobilemanager.MainActivity"
)
}
val list = context.getPackageManager().queryIntentActivities(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
if (list.size > 0) {
context.startActivity(intent)
}
val notificationIntent = Intent(context, GreenHCMActivity::class.java)
val bundle = Bundle()
notificationIntent.putExtras(bundle)
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
//val contentIntent = PendingIntent.getActivity(
// context,
//1,
//notificationIntent,
//PendingIntent.FLAG_UPDATE_CURRENT
//)
var contentIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//mNotificationManager.cancel(1)
// mNotificationManager.cancelAll()
if (android.os.Build.VERSION.SDK_INT >= 26)
{
val mChannel = NotificationChannel(
CHANNEL_ID,
name,
NotificationManager.IMPORTANCE_HIGH
)
mNotificationManager.createNotificationChannel(mChannel)
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setDefaults(DEFAULT_ALL)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
.setAutoCancel(true)
// Overrides ContentTitle in the big form of the template.
.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
.setContentIntent(contentIntent);
//.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
}
else
{
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
//.setPriority(NotificationCompat.PRIORITY_MAX)
.setPriority(Notification.PRIORITY_HIGH)
//lollipop, marshmallow, nougat
.setContentTitle("Selamat Pagi Jangan Lupa Untuk Absensi ")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(
BitmapFactory.decodeResource(
context.resources,
R.drawable.absence
)
)
.setSummaryText("Mohon melakukan absensi pagi ini,Terima kasih")
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
)
}
mBuilder.setContentIntent(contentIntent)
.setDefaults(DEFAULT_ALL)
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
val note = mBuilder.build()
mBuilder.setContentText("Mohon melakukan absensi pagi ini,Terima kasih")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(BitmapFactory.decodeResource(context.resources, R.drawable.absence))
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
// Set the first line of text after the detail section in the big form of the template.
//.setSummaryText("Mohon melakukan absensi pagi ini,Terima kasih")
)
mNotificationManager.notify(1, mBuilder.build())
}
}
below my code Alarmbroadcastreceiver2 for show 16PM :
class AlarmBroadcastReceiver2: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
showNotification(context)
}
internal fun showNotification(context: Context) {
val CHANNEL_ID = "1"// The id of the channel.
val name = context.getResources().getString(R.string.app_name)// The user-visible name of the channel.
val mBuilder: NotificationCompat.Builder
val notificationIntent = Intent(context, GreenHCMActivity::class.java)
val bundle = Bundle()
notificationIntent.putExtras(bundle)
val intent = Intent()
val manufacturer = android.os.Build.MANUFACTURER
when(manufacturer) {
"xiaomi" ->
intent.component =
ComponentName(
"com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"
)
"oppo" ->
intent.component =
ComponentName(
"com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity"
)
"vivo" ->
intent.component =
ComponentName(
"com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity"
)
}
val list = context.getPackageManager().queryIntentActivities(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
if (list.size > 0) {
context.startActivity(intent)
}
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
//notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP )
//val contentIntent = PendingIntent.getActivity(
// context,
//1,
//notificationIntent,
//PendingIntent.FLAG_UPDATE_CURRENT
//)
val contentIntent = PendingIntent.getActivity(
context,
1,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//mNotificationManager.cancel(2);
//mNotificationManager.cancelAll();
if (android.os.Build.VERSION.SDK_INT >= 26)
{
val mChannel = NotificationChannel(
CHANNEL_ID,
name,
NotificationManager.IMPORTANCE_HIGH,
)
mNotificationManager.createNotificationChannel(mChannel)
//mNotificationManager.cancel(1)
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLights(Color.RED, 300, 300)
.setChannelId(CHANNEL_ID)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setDefaults(DEFAULT_ALL)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
.setAutoCancel(true)
.setContentTitle("Selamat Sore Jangan Lupa Untuk Absensi")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(
BitmapFactory.decodeResource(
context.resources,
R.drawable.absence2_2
)
)
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
// Overrides ContentTitle in the big form of the template.
//.setBigContentTitle("Selamat Sore Jangan Lupa Untuk Absensi ")
// Set the first line of text after the detail section in the big form of the template.
//.setSummaryText("")
)
}
else
{
mBuilder = NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
//.setPriority(NotificationCompat.PRIORITY_MAX)
.setPriority(Notification.PRIORITY_HIGH)
//lollipop, marshmallow, nougat
.setContentTitle("Selamat Sore Jangan Lupa Untuk Absensi")
.setStyle(
NotificationCompat.BigPictureStyle()
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(
BitmapFactory.decodeResource(
context.resources,
R.drawable.absence2_2
)
)
.setSummaryText("Mohon melakukan absensi sore ini,Terima kasih")
// Override the large icon when the big notification is shown.
.bigLargeIcon(
BitmapFactory.decodeResource(
context.resources,
R.mipmap.ic_launcher_round
)
)
)
}
mBuilder.setContentIntent(contentIntent)
mBuilder.setContentText("Mohon melakukan absensi sore ini,Terima kasih")
.setDefaults(DEFAULT_ALL)
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round)
val note = mBuilder.build()
//mBuilder.setContentText("Yth Kepada Seluruh Karyawan dimohon untuk melakukan absensi di pagi ini,Terima Kasih")
mNotificationManager.notify(1, mBuilder.build())
//mNotificationManager.cancel(1)
}
}
ниже внутри oncreate будет вызываться 2 разных раза:
//notif4 16.00 evening
val _intent2 = Intent(this, AlarmBroadcastReceiver2::class.java)
val pendingIntent2 = PendingIntent.getBroadcast(this, 1, _intent2, 0)
val alarmManager2 = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
//alarmManager2.cancel(pendingIntent2)
//val calendar2 = Calendar.getInstance()
val calendar2 = getInstance()
//calendar2.setTimeInMillis(System.currentTimeMillis())
calendar2.set(Calendar.HOUR_OF_DAY, 16)
calendar2.set(Calendar.MINUTE, 18)
calendar2.set(Calendar.SECOND, 0)
//calendar2.set(Calendar.AM_PM,Calendar.PM);
alarmManager2.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2 )
//notif3 07:00 morning
val _intent = Intent(this, AlarmBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 2, _intent, 0)
val alarmManager = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
val calendar = getInstance()
//calendar.setTimeInMillis(System.currentTimeMillis())
calendar.set(Calendar.HOUR_OF_DAY, 7)
calendar.set(Calendar.MINUTE, 1)
calendar.set(Calendar.SECOND, 0)
//calendar.set(Calendar.AM_PM,Calendar.AM);
alarmManager.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent )
Как это решить? Привет, я новичок-разработчик kotlin, я хочу показывать push-уведомления в kotlin в 7 утра и 16 вечера каждый день, здесь я делаю 2 широковещательных приемника и 2 объявляю время внутри oncreate, но иногда push-уведомления не отображаются, я не знаю, заблокирован ли приемник miui saver, потому что иногда отображаются, но не в то время…. Мне нужна дополнительная помощь для решения, большое вам спасибо…..
Комментарии:
1. AlaramManager не работает после уничтожения приложения следующие устройства: OPPO, VIVO, MI или некоторые китайские телефоны на базе ОС
2. можете ли вы дать мне решение для этого, сэр? теперь я чувствую себя сбитым с толку
3. перед убийством push-уведомление тоже может не отображаться, а иногда push-уведомление отображается в неподходящее время: ( пример: установлено 7 утра, но push-уведомление отображается в 05:30 утра 🙁
4. извините, но ни одно решение в alaram manager не отправляет push-уведомления с помощью firebase. эта проблема обнаруживает только мобильные устройства и ОС
5. я не использую firebase, сэр, только локально в mainactivity