使用警报管理器的Android警报通知

时间:2018-10-20 06:21:48

标签: java android alarmmanager

   bookAppoinmentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
              setAlarm(String time, String strDate);
            }
        });  
  public void setAlarm(String time, String strDate){
        AlarmManager manager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);

        Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
        String hour=formateDateFromstring("HH:mm","HH",time);
        String min=formateDateFromstring("HH:mm","mm",time);
        String date=formateDateFromstring("yyyy-MM-dd","dd",strDate);
        String month=formateDateFromstring("yyyy-MM-dd","MM",strDate);
        String year=formateDateFromstring("yyyy-MM-dd","yyyy",strDate);

        cal.set(Calendar.DATE, Integer.parseInt(date));  //1-31
        cal.set(Calendar.MONTH, Integer.parseInt(month));  //first month is 0!!! January is zero!!!
        cal.set(Calendar.YEAR, Integer.parseInt(year));//year...
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));  //HOUR
        cal.set(Calendar.MINUTE, Integer.parseInt(min));       //MIN

        manager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                pendingIntent);
    }

在这里,我正在使用警报管理器发送选定时间和日期的通知。在与项目集成后,我尝试了具有相同代码的示例项目。

//这是我给接收者的代码

public class ServiceReceiver extends BroadcastReceiver {
    private Context mcontext;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.mcontext = context;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.logob_icon_prestigesalon)
                .setContentTitle("ABC")
                .setContentText("time to go")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManager notificationmanager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationmanager.notify(0, builder.build());


    }
}

1 个答案:

答案 0 :(得分:0)

经过大量搜索,我找到了如何在 Kotlin 中使用警报管理器发送通知。我添加了以下内容。在这里,我安排了每分钟的警报,以便它会在每分钟触发(就我而言,检查 Realm 数据库中的时间,并在该特定时间触发通知)。即使您的应用程序关闭(从最近的任务中删除),此通知也会触发。但我不知道这是否是正确的方法。我已经在 Android R(11) 和模拟器上进行了测试,在这两种情况下都可以正常工作。

创建以下函数并从您的活动中调用

 private fun scheduleAlarm() {
    val alarmIntent = Intent(this, AlarmReceiver::class.java)
    alarmIntent.putExtra("data", "Pass your message")
    val pendingIntent =
        PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT)
    val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
    val afterOneMinutes = SystemClock.elapsedRealtime() + 1 * 1 * 1000

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) alarmManager.setInexactRepeating(
        AlarmManager.ELAPSED_REALTIME_WAKEUP, afterTwoMinutes, 1000 * 1, pendingIntent
    ) else alarmManager.setExact(
        AlarmManager.ELAPSED_REALTIME_WAKEUP,
        afterOneMinutes , pendingIntent
    )

}

您可以在这里设置重复时间, val afterOneMinutes = SystemClock.elapsedRealtime() + 1 * 1 * 1000 在这里,我每隔一分钟重复一次。

主要逻辑在 Broadcast Receiver 类(我的案例)

class AlarmReceiver : BroadcastReceiver() {

@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context, intent: Intent) {
    Log.e("TAG", "Alarm received")

    if("Your Condition")
    {
        sendNotification(context, intent.getStringExtra("data"))
    }

}

@RequiresApi(Build.VERSION_CODES.O)
fun sendNotification(mcontext: Context, messageBody: String?)
{
    val intent = Intent(mcontext, YourActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    val pendingIntent = PendingIntent.getActivity(
        mcontext, 0 /* Request code */, intent,
        PendingIntent.FLAG_UPDATE_CURRENT
    )
    val notificationManager =
        mcontext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val defaultSoundUri: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val notificationChannel = NotificationChannel(
            mcontext.getString(R.string.default_notification_channel_id),
            "Rewards Notifications",
            NotificationManager.IMPORTANCE_DEFAULT
        )

        // Configure the notification channel.
        notificationChannel.description = "Channel description"
        notificationChannel.enableLights(true)
        notificationChannel.lightColor = Color.GREEN
        notificationChannel.vibrationPattern = longArrayOf(0, 500, 200, 500)
        notificationChannel.enableVibration(true)
        notificationManager.createNotificationChannel(notificationChannel)
    }
    val notificationBuilder = Notification.Builder(
        mcontext,
        mcontext.getString(R.string.default_notification_channel_id)
    )
        .setContentTitle(mcontext.getString(R.string.app_name))
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setSmallIcon(R.drawable.app_icon)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent)
    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
}

}

在这里,我在 onReceive() 方法中设置了一个条件。如果条件为真,则触发通知。您还可以根据需要使用 firebase 实时数据库更改、时间更改、数据库更改或任何其他条件。

不要忘记在清单中注册接收者

我希望它对某些人有用并且编码愉快........