Anonymous
Android Studio, я не могу активировать уведомления после того, как отклонил их
Сообщение
Anonymous » 31 май 2024, 21:19
Я хочу создать кнопку SwitchCompat, которая управляет уведомлением приложения. Когда пользователь активирует эту кнопку, я хочу отправить ему/ей уведомление с надписью «Хотите ли вы получать уведомления от этого приложения», и если пользователь нажимаю "да" хочу активировать уведомления. Все хорошо, но после того, как пользователь нажмет «Да» или «Нет», я не могу изменить настройки уведомлений, поэтому пользователь не может закрыть или открыть их по своему желанию, чего я не хочу.
XML-файл
AndroidManifest.XML
Java-файл
Код: Выделить всё
private static final String CHANNEL_ID = "notification_channel";
private static final int NOTIFICATION_ID = 1;
private static final int REQUEST_CODE_NOTIFICATION_PERMISSION = 100;
private SwitchCompat notificationSwitch;
private SharedPreferences sharedPreferences;
private static final String PREFS_NAME = "prefs";
private static final String PREF_NOTIFICATION_ENABLED = "notification_enabled";
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_tab);
notificationSwitch = findViewById(R.id.notificationSwitch);
sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
// Check the switch button status
boolean isNotificationEnabled = sharedPreferences.getBoolean(PREF_NOTIFICATION_ENABLED, false);
notificationSwitch.setChecked(isNotificationEnabled);
createNotificationChannel();
notificationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(SettingsActivity.this, android.Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SettingsActivity.this,
new String[]{android.Manifest.permission.POST_NOTIFICATIONS},
REQUEST_CODE_NOTIFICATION_PERMISSION);
}
else {
showNotification();
saveNotificationPreference(true);
}
}
else {
showNotification();
saveNotificationPreference(true);
}
}
else {
saveNotificationPreference(false);
}
}
});
}
//Outside of the onCreate
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_NOTIFICATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showNotification();
saveNotificationPreference(true);
}
else {
notificationSwitch.setChecked(false);
}
}
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notification Channel";
String description = "Channel for notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
private void showNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.notification_permission))
.setContentText(getString(R.string.notification_alert))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
private void saveNotificationPreference(boolean isEnabled) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(PREF_NOTIFICATION_ENABLED, isEnabled);
editor.apply();
}
Я знаю, что комментариев нет, сначала хотелось доделать функционал кода, потом добавлю комментарии.
Подробнее здесь:
https://stackoverflow.com/questions/785 ... eclined-it
1717179589
Anonymous
Я хочу создать кнопку SwitchCompat, которая управляет уведомлением приложения. Когда пользователь активирует эту кнопку, я хочу отправить ему/ей уведомление с надписью «Хотите ли вы получать уведомления от этого приложения», и если пользователь нажимаю "да" хочу активировать уведомления. Все хорошо, но после того, как пользователь нажмет «Да» или «Нет», я не могу изменить настройки уведомлений, поэтому пользователь не может закрыть или открыть их по своему желанию, чего я не хочу. [b]XML-файл[/b] [code] [/code] [b]AndroidManifest.XML[/b] [code] [/code] [b]Java-файл[/b] [code]private static final String CHANNEL_ID = "notification_channel"; private static final int NOTIFICATION_ID = 1; private static final int REQUEST_CODE_NOTIFICATION_PERMISSION = 100; private SwitchCompat notificationSwitch; private SharedPreferences sharedPreferences; private static final String PREFS_NAME = "prefs"; private static final String PREF_NOTIFICATION_ENABLED = "notification_enabled"; protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings_tab); notificationSwitch = findViewById(R.id.notificationSwitch); sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // Check the switch button status boolean isNotificationEnabled = sharedPreferences.getBoolean(PREF_NOTIFICATION_ENABLED, false); notificationSwitch.setChecked(isNotificationEnabled); createNotificationChannel(); notificationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(SettingsActivity.this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(SettingsActivity.this, new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, REQUEST_CODE_NOTIFICATION_PERMISSION); } else { showNotification(); saveNotificationPreference(true); } } else { showNotification(); saveNotificationPreference(true); } } else { saveNotificationPreference(false); } } }); } //Outside of the onCreate @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_NOTIFICATION_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showNotification(); saveNotificationPreference(true); } else { notificationSwitch.setChecked(false); } } } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "Notification Channel"; String description = "Channel for notification"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } private void showNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(getString(R.string.notification_permission)) .setContentText(getString(R.string.notification_alert)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setAutoCancel(true); Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName()); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); builder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, builder.build()); } private void saveNotificationPreference(boolean isEnabled) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(PREF_NOTIFICATION_ENABLED, isEnabled); editor.apply(); } [/code] Я знаю, что комментариев нет, сначала хотелось доделать функционал кода, потом добавлю комментарии. Подробнее здесь: [url]https://stackoverflow.com/questions/78561613/android-studio-i-cant-activate-notifications-after-i-declined-it[/url]