Monday, 17 August 2020

Create a alarm manager to trigger at 9.30 PM everyday and display a notification to the user

  No comments
Hello Everyone, In the code, I just simply trigger an alarm at 9.30 PM every day and show a notification to the user. You can modify the code according to you need For more detailed information you can visit official android website https://developer.android.com/training/scheduling/alarms
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//set alarm time to 9:30 PM to trigger
val calendar: Calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 21)
calendar.set(Calendar.MINUTE, 30)
calendar.set(Calendar.SECOND, 0)
val al = com.app.base.ReminderServices.AlarmReceiver()
al.setAlarm(this@MainActivity, calendar, Random().nextInt(10) + 1)
}
package com.app.base.ReminderServices
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import java.util.*
/**
* Created by Suraj Bahadur on 17-Aug-20.
*/
class AlarmBootReceiver : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
try {
if (intent!!.action == "android.intent.action.BOOT_COMPLETED") {
// Set the alarm here.
val calendar: Calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 21)
calendar.set(Calendar.MINUTE, 30)
calendar.set(Calendar.SECOND, 0)
val al = AlarmReceiver()
al.setAlarm(ctx!!, calendar, Random().nextInt(10) + 1)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
package com.app.base.ReminderServices
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.provider.Settings
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.legacy.content.WakefulBroadcastReceiver
import com.app.base.R
import com.app.base.activity.MainActivity
import java.util.*
class AlarmReceiver : WakefulBroadcastReceiver() {
var mAlarmManager: AlarmManager? = null
var mPendingIntent: PendingIntent? = null
override fun onReceive(context: Context, intent: Intent) {
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("default", CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
channel.description = "温馨提示:請把回收桶掛於門外,以便明天上午九時至下午六時回收。若回收時段內沒有把回收桶掛於門外,本星期將不會回收"
channel.lightColor = Color.parseColor("#067EE8")
mNotificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(context, "default")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.dustbin))
.setContentTitle("回收通知") // title for notification
.setContentText("温馨提示:請把回收桶掛於門外,以便明天上午九時至下午六時回收。若回收時段內沒有把回收桶掛於門外,本星期將不會回收") // message for notification
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI) // set alarm sound for notification
.setChannelId("default")
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setAutoCancel(true) // clear notification after click
val intent1 = Intent(context, MainActivity::class.java)
val pi = PendingIntent.getActivity(context, 0, intent1, PendingIntent.FLAG_ONE_SHOT)
mBuilder.setContentIntent(pi)
mNotificationManager.notify(0, mBuilder.build())
}
fun setAlarm(context: Context, calendar: Calendar, ID: Int) {
mAlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Put Reminder ID in Intent Extra
val intent = Intent(context, AlarmReceiver::class.java)
intent.putExtra("TaskID_Alarm", Integer.toString(ID))
mPendingIntent = PendingIntent.getBroadcast(context, ID, intent, PendingIntent.FLAG_CANCEL_CURRENT)
// Calculate notification time
val c = Calendar.getInstance()
mAlarmManager!!.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, mPendingIntent)
// Restart alarm if device is rebooted
val receiver = ComponentName(context, AlarmBootReceiver::class.java)
context.packageManager.setComponentEnabledSetting(
receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)
}
companion object {
const val CHANNEL_NAME = "test"
}
}
//Set the RECEIVE_BOOT_COMPLETED permission in your application's manifest. This allows your app
//to receive the ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting (this only works if
//the app has already been launched by the user at least once):
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".ReminderServices.AlarmReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>

No comments :

Post a Comment