簡體   English   中英

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

[英]Android alert notification using alarm manager

   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());


    }
}

經過大量搜索,我找到了如何在 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 實時數據庫更改、時間更改、數據庫更改或任何其他條件。

不要忘記在清單中注冊接收器

我希望它對某些人有用並且快樂編碼........

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM