BroadcastReceiver that handles daily notifications for favorite currency exchange rates.
*/
public class DailyNotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Access the SharedPreferences where favorite currency pairs are stored
SharedPreferences prefs = context.getSharedPreferences("favorites", Context.MODE_PRIVATE);
// Retrieve the set of favorite currency pairs
Set<String> favoritePairs = prefs.getStringSet("favorite_pairs", null);
// Proceed only if there are favorite pairs to report
if (favoritePairs != null && !favoritePairs.isEmpty()) {
StringBuilder contentBuilder = new StringBuilder();
// Create an instance of CurrencyRepository to access exchange rates
CurrencyRepository repository = new CurrencyRepository(context);
// Loop through each favorite currency pair
for (String pair : favoritePairs) {
// Split the pair into base currency and target currency
String[] currencies = pair.split("/");
// Ensure that the pair is valid with exactly two currencies
if (currencies.length == 2) {
String fromCurrency = currencies[0]; // Base currency
String toCurrency = currencies[1]; // Target currency
// Fetch the latest exchange rate from the repository
Double rate = repository.getExchangeRate(fromCurrency, toCurrency);
if (rate != null) {
// Append the formatted exchange rate to the notification content
contentBuilder.append(String.format("%s/%s: %.4f\n", fromCurrency, toCurrency, rate));
} else {
// Handle case where exchange rate data is not available
contentBuilder.append(String.format("%s/%s: нет данных\n", fromCurrency, toCurrency));
}
} else {
// Handle invalid pair format
contentBuilder.append(String.format("%s: неверный формат пары\n", pair));
}
}
String contentText = contentBuilder.toString();
// Build and display the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "daily_rate_channel")
.setContentTitle("Курсы избранных валют")
.setContentText(contentText)
.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText)) // Supports longer text
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
// Get the NotificationManager service to display the notification
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Display the notification with a unique ID
if (notificationManager != null) {
notificationManager.notify(1, builder.build());
}
} else {
// Optionally handle the case when there are no favorite pairs
// For example, you might log this information or skip notification
}
}
} package com.example.myapplication;
// RecyclerView to display the list of favorite currency pairs
private RecyclerView recyclerView;
// Adapter to manage the data and bind it to the RecyclerView
private CurrencyAdapter currencyAdapter;
// Repository to fetch currency data
private CurrencyRepository repository;
// Set to store favorite currency pairs
private Set<String> favoriteCurrencyPairs;
// TextView to display when no favorite pairs exist
private TextView textEmpty;
private Switch switchDailyNotifications;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_list);
// Initialize the repository
repository = new CurrencyRepository(this);
// Retrieve favorite currency pairs from SharedPreferences
favoriteCurrencyPairs = getFavoriteCurrencyPairs();
// Initialize RecyclerView and set its layout manager
recyclerView = findViewById(R.id.currency_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Reference to the empty state TextView
textEmpty = findViewById(R.id.text_empty);
// Initialize the adapter with the list of favorite pairs and set the click listener
currencyAdapter = new CurrencyAdapter(new ArrayList<>(favoriteCurrencyPairs), new CurrencyAdapter.OnFavoriteClickListener() {
@Override
public void onFavoriteClick(String currencyPair, boolean isFavorite) {
// Handle the favorite button click
if (isFavorite) {
// If marking as favorite (adding)
favoriteCurrencyPairs.add(currencyPair);
Toast.makeText(CurrencyListActivity.this, "Добавлено в избранное: " + currencyPair, Toast.LENGTH_SHORT).show();
} else {
// If unmarking as favorite (removing)
favoriteCurrencyPairs.remove(currencyPair);
Toast.makeText(CurrencyListActivity.this, "Удалено из избранного: " + currencyPair, Toast.LENGTH_SHORT).show();
}
// Save the updated favorite pairs to SharedPreferences
saveFavoriteCurrencyPairs(favoriteCurrencyPairs);
// Update the UI to reflect changes
updateUI();
}
});
// Set the adapter to the RecyclerView
recyclerView.setAdapter(currencyAdapter);
switchDailyNotifications = findViewById(R.id.switch_daily_notifications);
// Retrieve saved state
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
boolean isNotificationsEnabled = prefs.getBoolean("daily_notifications_enabled", false);
switchDailyNotifications.setChecked(isNotificationsEnabled);
// Set up listener
switchDailyNotifications.setOnCheckedChangeListener((buttonView, isChecked) -> {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("daily_notifications_enabled", isChecked);
editor.apply();
if (isChecked) {
scheduleDailyNotification();
} else {
cancelDailyNotification();
}
});
// Initialize and set the "Back" button listener to finish the activity
Button backButton = findViewById(R.id.button_back);
backButton.setOnClickListener(v -> finish());
// Initialize and set the "Add Pair" button listener to open the add pair dialog
Button addPairButton = findViewById(R.id.button_add_pair);
addPairButton.setOnClickListener(v -> new LoadCurrenciesTaskForDialog().execute());
// Update the UI based on whether there are favorite pairs
updateUI();
}
/**
* Retrieves the set of favorite currency pairs from SharedPreferences.
*
* @return A new HashSet containing the favorite currency pairs.
*/
private Set<String> getFavoriteCurrencyPairs() {
SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
Set<String> defaultSet = new HashSet<>();
Set<String> storedSet = prefs.getStringSet("favorite_pairs", defaultSet);
// Return a new HashSet to avoid modifying the original set from SharedPreferences
return new HashSet<>(storedSet);
}
/**
* Saves the updated set of favorite currency pairs to SharedPreferences.
*
* @param favorites The set of favorite currency pairs to save.
*/
private void saveFavoriteCurrencyPairs(Set<String> favorites) {
SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet("favorite_pairs", favorites);
editor.apply();
}
/**
* Updates the UI by toggling the visibility of the RecyclerView and the empty state TextView.
*/
private void updateUI() {
if (favoriteCurrencyPairs.isEmpty()) {
// If there are no favorite pairs, show the empty state message and hide the RecyclerView
recyclerView.setVisibility(View.GONE);
textEmpty.setVisibility(View.VISIBLE);
} else {
// If there are favorite pairs, show the RecyclerView and hide the empty state message
recyclerView.setVisibility(View.VISIBLE);
textEmpty.setVisibility(View.GONE);
}
}
/**
* AsyncTask to load the list of currencies in the background for the add pair dialog.
*/
private class LoadCurrenciesTaskForDialog extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(Void... voids) {
// Fetch all unique currencies from the repository
return repository.getAllUniqueCurrencies();
}
@Override
protected void onPostExecute(List<String> currencies) {
if (currencies != null && !currencies.isEmpty()) {
// If currencies are available, show the add pair dialog
showAddPairDialog(currencies);
} else {
// If no currencies are available, inform the user
Toast.makeText(CurrencyListActivity.this, "Нет доступных валют для добавления.", Toast.LENGTH_SHORT).show();
}
}
}
/**
* Displays an AlertDialog allowing the user to select and add a new currency pair.
*
* @param currencies A list of available currency codes.
*/
private void showAddPairDialog(List<String> currencies) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Добавить валютную пару");
// Inflate the custom dialog layout
LayoutInflater inflater = LayoutInflater.from(this);
View dialogView = inflater.inflate(R.layout.dialog_add_pair, null);
Spinner spinnerBase = dialogView.findViewById(R.id.spinner_base);
Spinner spinnerTarget = dialogView.findViewById(R.id.spinner_target);
// Set up the adapters for the spinners
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, currencies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerBase.setAdapter(adapter);
spinnerTarget.setAdapter(adapter);
// Set the custom view to the dialog
builder.setView(dialogView);
// Define the positive button action (Add)
builder.setPositiveButton("Добавить", (dialog, which) -> {
String base = spinnerBase.getSelectedItem().toString();
String target = spinnerTarget.getSelectedItem().toString();
// Validate that base and target currencies are not the same
if (base.equals(target)) {
Toast.makeText(this, "Базовая и целевая валюты не могут быть одинаковыми.", Toast.LENGTH_SHORT).show();
return;
}
String pair = base + "/" + target;
// Check if the pair already exists in favorites
if (favoriteCurrencyPairs.contains(pair)) {
Toast.makeText(this, "Эта пара уже добавлена в избранное.", Toast.LENGTH_SHORT).show();
return;
}
// Add the new pair to favorites
favoriteCurrencyPairs.add(pair);
saveFavoriteCurrencyPairs(favoriteCurrencyPairs);
// Update the adapter with the new pair
currencyAdapter.addCurrencyPair(pair);
// Inform the user
Toast.makeText(this, "Добавлено в избранное: " + pair, Toast.LENGTH_SHORT).show();
// Update the UI to reflect changes
updateUI();
});
// Define the negative button action (Cancel)
builder.setNegativeButton("Отмена", (dialog, which) -> dialog.dismiss());
// Show the dialog
builder.show();
}
private void scheduleDailyNotification() {
// Create notification channel for Android O and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Daily Rate Channel";
String description = "Channel for daily exchange rate notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("daily_rate_channel", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
// Schedule the alarm
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, DailyNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// Set the time to 00:01
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
// If the time is before now, schedule for next day
if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
// Set the repeating alarm
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
private void cancelDailyNotification() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, DailyNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
if (alarmManager != null) {
alarmManager.cancel(pendingIntent);
}
}
Понимаю, что вы столкнулись с проблемой, когда при изменении системного времени на устройстве уведомление не срабатывает как ожидается. Это распространённая проблема при использовании AlarmManager с методом setRepeating(), особенно когда системное время изменяется вручную. Давайте рассмотрим возможные причины и предложим решения для обеспечения стабильной работы уведомлений.
Возможные причины проблемы
-
Использование setRepeating():
Метод setRepeating() задаёт повторяющиеся будильники, но начиная с Android API 19 (KitKat), эти будильники становятся "нечёткими" (inexact) для оптимизации энергопотребления. Это означает, что гарантировать точное время срабатывания сложно, особенно при изменении системного времени.
-
Изменение системного времени:
При изменении системного времени вручную, будильники, основанные на AlarmManager, могут не срабатывать должным образом, если они уже были запланированы. Например, если вы установили будильник на 00:01 и затем перевели время на 12:00, будильник может просто пропустить событие.
-
Регистрация BroadcastReceiver:
Если DailyNotificationReceiver не зарегистрирован должным образом в AndroidManifest.xml, то система не будет знать о вашем приёмнике, и уведомления не будут отправляться.
-
Флаги PendingIntent:
Неправильное использование флагов при создании PendingIntent может привести к тому, что намерение не распознаётся системой корректно.
Рекомендации и решения
Чтобы обеспечить более надёжную работу уведомлений, особенно в условиях изменения системного времени, рекомендуется перейти от использования setRepeating() к использованию setExactAndAllowWhileIdle(). Это позволяет установить точные будильники и перезапланировать следующий будильник после срабатывания текущего. Также рекомендуется рассмотреть использование WorkManager для периодических задач, так как он более устойчив к изменениям системного времени и рассматривает режимы энергосбережения.
Шаги для реализации решения:
-
Измените AlarmManager на использование setExactAndAllowWhileIdle():
Вместо использования setRepeating(), установите точный будильник, который будет срабатывать один раз, а в BroadcastReceiver устанавливайте следующий будильник.
private void scheduleDailyNotification() {
// Создание notification channel для Android O и выше
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Daily Rate Channel";
String description = "Channel for daily exchange rate notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("daily_rate_channel", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
// Планирование будильника
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, DailyNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// Настройка времени срабатывания на 00:01
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
// Если время уже прошло, установить на следующий день
if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
// Установка точного будильника
if (alarmManager != null) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
-
Перезапланируйте следующий будильник в BroadcastReceiver:
После срабатывания текущего будильника, необходимо установить следующий будильник на следующий день.
public class DailyNotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Ваш существующий код для отправки уведомления
// ...
// Перезапланировать следующий будильник
scheduleNextAlarm(context);
}
private void scheduleNextAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, DailyNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.DAY_OF_MONTH, 1); // Следующий день
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 0);
if (alarmManager != null) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
}
-
Убедитесь, что BroadcastReceiver зарегистрирован в AndroidManifest.xml:
Добавьте следующий код в ваш AndroidManifest.xml внутри тега <application>:
<receiver android:name=".DailyNotificationReceiver"
android:exported="false" />
-
Рассмотрите использование WorkManager для периодических задач:
WorkManager более устойчив к изменениям системного времени и режимам энергосбережения. Вот пример использования WorkManager для ежедневных уведомлений:
-
Добавьте зависимость в build.gradle:
implementation "androidx.work:work-runtime:2.7.1"
-
Создайте класс DailyNotificationWorker:
public class DailyNotificationWorker extends Worker {
public DailyNotificationWorker(@NonNull Context context, @NonNull WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public Result doWork() {
// Ваш код для отправки уведомления
Context context = getApplicationContext();
// ... (тот же код для отправки уведомления)
return Result.success();
}
}
-
Запланируйте периодическую задачу в CurrencyListActivity:
private void scheduleDailyWork() {
PeriodicWorkRequest dailyWorkRequest = new PeriodicWorkRequest.Builder(
DailyNotificationWorker.class,
1,
TimeUnit.DAYS)
.setInitialDelay(calculateInitialDelay(), TimeUnit.MILLISECONDS)
.build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"DailyNotificationWork",
ExistingPeriodicWorkPolicy.REPLACE,
dailyWorkRequest);
}
private long calculateInitialDelay() {
Calendar currentDate = Calendar.getInstance();
Calendar dueDate = Calendar.getInstance();
dueDate.set(Calendar.HOUR_OF_DAY, 0);
dueDate.set(Calendar.MINUTE, 1);
dueDate.set(Calendar.SECOND, 0);
if(dueDate.before(currentDate)) {
dueDate.add(Calendar.HOUR_OF_DAY, 24);
}
return dueDate.getTimeInMillis() - currentDate.getTimeInMillis();
}
Вызывайте scheduleDailyWork() при включении уведомлений.
Дополнительные рекомендации
-
Проверка уведомлений:
Убедитесь, что уведомления работают корректно, используя обычный режим времени без изменений. Это поможет подтвердить, что основная логика работает правильно.
-
Логирование:
Добавьте логирование (Log.d) в ключевые места вашего кода (onReceive, установка будильника и т.д.), чтобы отслеживать, когда именно выполняются различные этапы.
-
Убедитесь в разрешениях:
Проверьте, что ваше приложение имеет все необходимые разрешения для отправки уведомлений и использования AlarmManager.
-
Тестирование на реальных устройствах:
Некоторые эмуляторы могут некорректно обрабатывать изменения системного времени. Рекомендуется тестировать на реальных устройствах для более точных результатов.
Заключение
Изменение подхода к планированию уведомлений поможет сделать их более надёжными и устойчивыми к изменениям системного времени. Использование setExactAndAllowWhileIdle() с перезапланированием будильников предоставляет больший контроль и точность, тогда как WorkManager обеспечивает устойчивость и удобство для периодических задач. Выберите подходящий для вашего приложения метод и протестируйте его в различных условиях, чтобы обеспечить стабильную работу уведомлений.