package com.example.myapplication; import… · The Chat Archive
Explore / Programming package com.example.myapplication; import android.app.NotificationChannel; import… Save Share Download ▾ Reportpackage com.example.myapplication;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import java.util.Set;
public class DailyNotificationReceiver extends BroadcastReceiver {
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);
}
}
}
Assistant2024-11-16 08:22 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Nov 16, 2024
Added to archive Nov 16, 2026
ID 01m7h4294ggdvqv6vvhf9p7nknSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 37bdaaacef36ba77b74bc2608897724b
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
}package com.example.myapplication;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import java.util.Calendar;
public class CurrencyAlarmHelper {
private static final String TAG = "CurrencyAlarmHelper";
private static final String CHANNEL_ID = "daily_rate_channel";
private static final String CHANNEL_NAME = "Daily Rate Channel";
private static final String CHANNEL_DESCRIPTION = "Channel for daily exchange rate notifications";
public static void scheduleDailyNotification(Context context, int hour, int minute) {
createNotificationChannel(context);
cancelAllNotifications(context);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager == null) {
Log.e(TAG, "AlarmManager не доступен");
return;
}
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.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent
);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent
);
} else {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
pendingIntent
);
}
Log.d(TAG, "Уведомление установлено на " + calendar.getTime().toString());
}
public static void cancelAllNotifications(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager == null) {
Log.e(TAG, "AlarmManager не доступен");
return;
}
Intent intent = new Intent(context, DailyNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
alarmManager.cancel(pendingIntent);
Log.d(TAG, "Все уведомления и будильники отменены");
}
private static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
if (notificationManager == null) {
Log.e(TAG, "NotificationManager не доступен");
return;
}
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
);
channel.setDescription(CHANNEL_DESCRIPTION);
notificationManager.createNotificationChannel(channel);
Log.d(TAG, "Notification Channel создан");
} else {
Log.d(TAG, "Notification Channel уже существует");
}
}
}
}package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.d(TAG, "BOOT_COMPLETED получен");
SharedPreferences prefs = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
int hour = prefs.getInt("notification_hour", -1);
int minute = prefs.getInt("notification_minute", -1);
if (hour != -1 && minute != -1) {
CurrencyAlarmHelper.scheduleDailyNotification(context, hour, minute);
Log.d(TAG, "Повторное установление уведомления после перезагрузки");
}
}
}
}package com.example.myapplication;
import android.Manifest;
import android.app.TimePickerDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CurrencyListActivity extends AppCompatActivity {
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();
}
} при выборе времени для оповещения приложение крашается
The crash you're experiencing when selecting the notification time is likely due to the use of the PendingIntent.FLAG_IMMUTABLE flag without proper version checks. This flag was introduced in API level 23 (Android 6.0 Marshmallow). If your app runs on devices with an API level lower than 23, using this flag without checking the API level will cause a crash.
Problem Explanation:
In your CurrencyAlarmHelper.java, you're using the PendingIntent.FLAG_IMMUTABLE flag directly in the PendingIntent.getBroadcast method:
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
Similarly, in the cancelAllNotifications method, you're using the same flags.
Why This Causes a Crash:
API Level: PendingIntent.FLAG_IMMUTABLE is available only on API level 23 and above.
No Version Check: Using this flag without checking the device's API level results in a crash on devices running API level 22 (Android 5.1 Lollipop) or lower because the flag value isn't recognized.
Exception Thrown: The system throws an IllegalArgumentException or NoSuchFieldError because it doesn't recognize the FLAG_IMMUTABLE constant.
Solution:
You need to modify your code to include a version check before using PendingIntent.FLAG_IMMUTABLE. Here's how you can do it:
Define Flags with Version Check:
int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
pendingIntentFlags |= PendingIntent.FLAG_IMMUTABLE;
}
Use Flags in getBroadcast:
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
pendingIntentFlags
);
Apply This Change Wherever PendingIntent is Used:
Ensure you apply this change in both the scheduleDailyNotification and cancelAllNotifications methods, or anywhere else you use PendingIntent.
Updated Code Snippets:
In CurrencyAlarmHelper.java - scheduleDailyNotification Method:
public static void scheduleDailyNotification(Context context, int hour, int minute) {
createNotificationChannel(context);
cancelAllNotifications(context);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager == null) {
Log.e(TAG, "AlarmManager не доступен");
return;
}
Intent intent = new Intent(context, DailyNotificationReceiver.class);
int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
pendingIntentFlags |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
pendingIntentFlags
);
// Rest of your scheduling code...
}
In CurrencyAlarmHelper.java - cancelAllNotifications Method:
public static void cancelAllNotifications(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmManager == null) {
Log.e(TAG, "AlarmManager не доступен");
return;
}
Intent intent = new Intent(context, DailyNotificationReceiver.class);
int pendingIntentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
pendingIntentFlags |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
pendingIntentFlags
);
alarmManager.cancel(pendingIntent);
Log.d(TAG, "Все уведомления и будильники отменены");
}
Additional Considerations:
Check All PendingIntent Usages: Make sure to apply this change wherever you use PendingIntent, including in your DailyNotificationReceiver, if applicable.
Test on Different API Levels: Test your app on devices or emulators with different API levels to ensure compatibility.
Exception Handling: Consider adding try-catch blocks around code that might throw exceptions due to API differences, although proper version checks should prevent this.
Explanation in Russian (Перевод на русский):
Краш приложения при выборе времени уведомления возникает из-за использования флага PendingIntent.FLAG_IMMUTABLE без проверки версии API. Этот флаг был введен в API уровне 23 (Android 6.0 Marshmallow). Если ваше приложение запускается на устройствах с API уровнем ниже 23, использование этого флага без проверки вызываем краш, так как система не распознает этот флаг.
Что нужно сделать:
Добавьте проверку версии API перед использованием флага PendingIntent.FLAG_IMMUTABLE.
Обновите код , чтобы использовать флаг только на устройствах с API уровнем 23 и выше.
Исправьте все места в коде , где используется PendingIntent, чтобы избежать подобных проблем.
Заключение:
После внесения этих изменений ваше приложение должно корректно работать при выборе времени уведомления, не вызывая краш на устройствах с более низкими версиями Android.
Copy first response
Not yet included in a published release.