private RecyclerView recyclerView;
private CurrencyAdapter currencyAdapter;
private CurrencyRepository repository;
private Set<String> favoriteCurrencyPairs;
private TextView textEmpty;
private TextView textSelectedTime;
private Button buttonSetTime;
private static final int REQUEST_NOTIFICATION_PERMISSION = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_list);
repository = new CurrencyRepository(this);
favoriteCurrencyPairs = getFavoriteCurrencyPairs();
recyclerView = findViewById(R.id.currency_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
textEmpty = findViewById(R.id.text_empty);
textSelectedTime = findViewById(R.id.text_selected_time);
currencyAdapter = new CurrencyAdapter(new ArrayList<>(favoriteCurrencyPairs), new CurrencyAdapter.OnFavoriteClickListener() {
@Override
public void onFavoriteClick(String currencyPair, boolean isFavorite) {
if (isFavorite) {
favoriteCurrencyPairs.add(currencyPair);
Toast.makeText(CurrencyListActivity.this, "Добавлено в избранное: " + currencyPair, Toast.LENGTH_SHORT).show();
} else {
favoriteCurrencyPairs.remove(currencyPair);
Toast.makeText(CurrencyListActivity.this, "Удалено из избранного: " + currencyPair, Toast.LENGTH_SHORT).show();
}
saveFavoriteCurrencyPairs(favoriteCurrencyPairs);
updateUI();
}
});
recyclerView.setAdapter(currencyAdapter);
buttonSetTime = findViewById(R.id.button_set_notification_time);
initializeNotificationTime();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestNotificationPermissionIfNeeded();
}
buttonSetTime.setOnClickListener(v -> showTimePickerDialog());
Button backButton = findViewById(R.id.button_back);
backButton.setOnClickListener(v -> finish());
Button addPairButton = findViewById(R.id.button_add_pair);
addPairButton.setOnClickListener(v -> new LoadCurrenciesTaskForDialog().execute());
updateUI();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_NOTIFICATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Разрешение на уведомления предоставлено", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Разрешение на уведомления отклонено. Уведомления не будут работать.", Toast.LENGTH_LONG).show();
textSelectedTime.setText("Время уведомлений: не установлено");
CurrencyAlarmHelper.cancelAllNotifications(this);
}
}
}
private Set<String> getFavoriteCurrencyPairs() {
SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
Set<String> defaultSet = new HashSet<>();
Set<String> storedSet = prefs.getStringSet("favorite_pairs", defaultSet);
return new HashSet<>(storedSet);
}
private void saveFavoriteCurrencyPairs(Set<String> favorites) {
SharedPreferences prefs = getSharedPreferences("favorites", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet("favorite_pairs", favorites);
editor.apply();
}
private void updateUI() {
if (favoriteCurrencyPairs.isEmpty()) {
recyclerView.setVisibility(View.GONE);
textEmpty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textEmpty.setVisibility(View.GONE);
}
}
private void initializeNotificationTime() {
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
int savedHour = prefs.getInt("notification_hour", -1);
int savedMinute = prefs.getInt("notification_minute", -1);
if (savedHour != -1 && savedMinute != -1) {
String time = String.format("%02d:%02d", savedHour, savedMinute);
textSelectedTime.setText("Время уведомлений: " + time);
} else {
textSelectedTime.setText("Время уведомлений: не установлено");
}
}
private void requestNotificationPermissionIfNeeded() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_NOTIFICATION_PERMISSION);
}
}
private void showTimePickerDialog() {
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
int savedHour = prefs.getInt("notification_hour", 8);
int savedMinute = prefs.getInt("notification_minute", 0);
TimePickerDialog timePickerDialog = new TimePickerDialog(this, (view, hourOfDay, minute) -> {
saveNotificationTime(hourOfDay, minute);
String time = String.format("%02d:%02d", hourOfDay, minute);
textSelectedTime.setText("Время уведомлений: " + time);
CurrencyAlarmHelper.scheduleDailyNotification(this, hourOfDay, minute);
Toast.makeText(this, "Уведомления будут отправляться в " + time, Toast.LENGTH_SHORT).show();
}, savedHour, savedMinute, true);
timePickerDialog.setTitle("Выберите время уведомлений");
timePickerDialog.show();
}
private void saveNotificationTime(int hour, int minute) {
SharedPreferences prefs = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notification_hour", hour);
editor.putInt("notification_minute", minute);
editor.apply();
}
private void cancelAllNotifications() {
CurrencyAlarmHelper.cancelAllNotifications(this);
}
private class LoadCurrenciesTaskForDialog extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(Void... voids) {
return repository.getAllUniqueCurrencies();
}
@Override
protected void onPostExecute(List<String> currencies) {
if (currencies != null && !currencies.isEmpty()) {
showAddPairDialog(currencies);
} else {
Toast.makeText(CurrencyListActivity.this, "Нет доступных валют для добавления.", Toast.LENGTH_SHORT).show();
}
}
}
private void showAddPairDialog(List<String> currencies) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Добавить валютную пару");
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);
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);
builder.setView(dialogView);
builder.setPositiveButton("Добавить", (dialog, which) -> {
String base = spinnerBase.getSelectedItem().toString();
String target = spinnerTarget.getSelectedItem().toString();
if (base.equals(target)) {
Toast.makeText(this, "Базовая и целевая валюты не могут быть одинаковыми.", Toast.LENGTH_SHORT).show();
return;
}
String pair = base + "/" + target;
if (favoriteCurrencyPairs.contains(pair)) {
Toast.makeText(this, "Эта пара уже добавлена в избранное.", Toast.LENGTH_SHORT).show();
return;
}
favoriteCurrencyPairs.add(pair);
saveFavoriteCurrencyPairs(favoriteCurrencyPairs);
currencyAdapter.addCurrencyPair(pair);
Toast.makeText(this, "Добавлено в избранное: " + pair, Toast.LENGTH_SHORT).show();
updateUI();
});
builder.setNegativeButton("Отмена", (dialog, which) -> dialog.dismiss());
builder.show();
}
private static final String CHANNEL_ID = "daily_rate_channel";
private static final String NOTIFICATION_TITLE = "Курсы избранных валют";
private static final int NOTIFICATION_ID = 1;
@Override
public void onReceive(Context context, Intent intent) {
try {
SharedPreferences prefs = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
Set<String> favoritePairs = prefs.getStringSet("favorite_pairs", null);
int notificationHour = prefs.getInt("notification_hour", -1);
int notificationMinute = prefs.getInt("notification_minute", -1);
if (favoritePairs != null && !favoritePairs.isEmpty() && notificationHour != -1 && notificationMinute != -1) {
StringBuilder contentBuilder = new StringBuilder();
CurrencyRepository repository = new CurrencyRepository(context);
for (String pair : favoritePairs) {
String[] currencies = pair.split("/");
if (currencies.length == 2) {
String fromCurrency = currencies[0];
String toCurrency = currencies[1];
Double rate = repository.getExchangeRate(fromCurrency, toCurrency);
if (rate != null) {
contentBuilder.append(String.format("%s/%s: %.4f\n", fromCurrency, toCurrency, rate));
} else {
contentBuilder.append(String.format("%s/%s: нет данных\n", fromCurrency, toCurrency));
}
} else {
contentBuilder.append(String.format("%s: неверный формат пары\n", pair));
}
}
String contentText = contentBuilder.toString();
createNotificationChannel(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.star)
.setContentTitle(NOTIFICATION_TITLE)
.setContentText("Курсы валют на сегодня")
.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
CurrencyAlarmHelper.scheduleDailyNotification(context, notificationHour, notificationMinute);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
if (notificationManager == null) {
return;
}
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Daily Rate Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
channel.setDescription("Channel for daily exchange rate notifications");
notificationManager.createNotificationChannel(channel);
}
}
}
It looks like the app is crashing when you choose the notification time because it's using the PendingIntent.FLAG_IMMUTABLE flag without checking the device's API level. This flag was introduced in API level 23 (Android M). If your app runs on devices with API levels lower than 23, using this flag without checking can cause a crash.
Here's how you can fix the issue:
1. Modify scheduleDailyNotification in CurrencyAlarmHelper.java:
Replace this line:
int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
With:
int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
pendingIntentFlags |= PendingIntent.FLAG_IMMUTABLE;
}
2. Modify cancelAllNotifications in CurrencyAlarmHelper.java:
Replace this line:
int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
With:
int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
pendingIntentFlags |= PendingIntent.FLAG_IMMUTABLE;
}
Explanation:
-
Why the Crash Happens:
- The
PendingIntent.FLAG_IMMUTABLE flag is only available in API level 23 and above.
- If your app is running on a device with an API level below 23, using this flag causes a
NoSuchFieldError or similar runtime exception, leading to a crash.
-
How the Fix Works:
- By checking the API level with
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M, you ensure that PendingIntent.FLAG_IMMUTABLE is only used on devices that support it.
- This prevents the app from crashing on devices with lower API levels.
3. Check Other Occurrences:
Make sure to update any other places in your code where you use PendingIntent.FLAG_IMMUTABLE without checking the API level. Always wrap it with an API level check as shown above.
4. Rebuild and Test Your App:
After making these changes, rebuild your app and test it on devices with different API levels to ensure that the crash is resolved.
Additional Recommendations:
- Logcat Output: If possible, check the logcat output when the crash occurs. It should give you a stack trace that points to the exact line causing the crash, confirming that it's due to
PendingIntent.FLAG_IMMUTABLE.
- Set Minimum SDK Version Appropriately: If your app requires features only available in newer API levels, you might consider setting a higher
minSdkVersion in your build.gradle file. However, in this case, conditional checks allow you to support older devices as well.
- Use Compatibility Libraries: Consider using AndroidX libraries or
PendingIntentCompat if available, as they help manage backward compatibility issues.
Summary:
The crash occurs because PendingIntent.FLAG_IMMUTABLE is being used without checking the device's API level. By conditionally including this flag only on devices running API level 23 or higher, you can prevent the crash and ensure your app runs smoothly on all supported devices.