Aşağıdaki kodla, veritabanında flashcard not verilerine reminderTime değeri ile alarm kuruyorum,şimdi ilgili notun alarmı çaldığında
uygulamam pushback mesajı göndererek notu hatırlatsın (Notification). Alarm kurma olayına seçenekler nasıl eklerim? Her 5dk her 10dk
Her saat, iki saatte bir, Her gün, iki günde bir, her hafta, haftasonnu vb... Bana bunları pratik ve basit entegre etmek için kodumu güncelle.Ana fonksiyonelliği kesinlikle bozma.
private boolean isReminderSet = false;
public long reminderTime;
Assistant
/**
Boş yapıcı metod.
*/
public FragmentEdit() {
// Gerekli boş yapıcı metod.
}
/**
Yeni bir instance oluşturur.
@param id Flashcard ID'si.
@param category Kategori adı.
@param title Başlık.
@param content İçerik.
@param favorite Favori durumu.
@param pinned Sabit durumu.
@param timestamp Oluşturulma zamanı.
@param updatedAt Güncellenme zamanı.
@param backgroundcolor Arka plan rengi.
@param hashtags Hashtag listesi.
@return Yeni FragmentEdit instance'ı.
*/
public static FragmentEdit newInstance(String id, String category, String title, String content, boolean favorite, boolean pinned, long timestamp, long updatedAt, String backgroundcolor, ArrayList hashtags) {
FragmentEdit fragment = new FragmentEdit();
Bundle args = new Bundle();
args.putString("id", id);
args.putString("category", category);
args.putString("title", title);
args.putString("content", content);
args.putBoolean("favorite", favorite);
args.putBoolean("pinned", pinned);
args.putString("backgroundColor", backgroundcolor);
args.putLong("timestamp", timestamp);
args.putLong("updatedAt", updatedAt);
args.putStringArrayList("hashtags", hashtags);
fragment.setArguments(args);
return fragment;
}
/**
Yeni bir instance oluşturur (yeni not).
@return Yeni FragmentEdit instance'ı.
*/
public static FragmentEdit newInstance() {
FragmentEdit fragment = new FragmentEdit();
Bundle args = new Bundle();
// Yeni not için varsayılan değerler
args.putString("id", null);
args.putString("category", "");
args.putString("title", "");
args.putString("content", "");
args.putBoolean("favorite", false);
args.putBoolean("pinned", false);
args.putString("backgroundColor", ""); // Varsayılan arka plan rengi
args.putLong("timestamp", System.currentTimeMillis());
args.putLong("updatedAt", System.currentTimeMillis());
args.putStringArrayList("hashtags", new ArrayList<>());
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Eğer fragment içinde kendi menünüzü kullanıyorsanız setHasOptionsMenu'a gerek olmayabilir.
// setHasOptionsMenu(true); // Gerekirse aktif edin.
if (getArguments() != null) {
SharedPreferencesManager sharedPreferencesManager = new SharedPreferencesManager(getActivity());
boolean isNightModeEnabled = sharedPreferencesManager.isNightModeEnabled();
code
// Arka plan rengi - boş olup olmadığını kontrol edin
backgroundColor = getArguments().getString("backgroundColor", ""); // Varsayılan boş string
int color;
if (backgroundColor == null || backgroundColor.isEmpty()) {
// Eğer arka plan rengi boşsa varsayılan bir renk kullanın (örneğin beyaz)
color = ContextCompat.getColor(getActivity(), R.color.backgroundColor); // Buradaki R.color.default olsun tercih ettiğiniz varsayılan
} else {
// Arka plan rengi tanımlıysa, rengi çözümleyin
try {
color = Color.parseColor(backgroundColor);
} catch (IllegalArgumentException e) {
// Geçersiz renk koduysa varsayılan rengi kullan
color = ContextCompat.getColor(getActivity(), R.color.backgroundColor);
}
}
// Gece ve gündüz modu renk dönüşümünü uygulayın
if (isNightModeEnabled) {
color = MainActivity.reverseColorMap.getOrDefault(color, color);
} else {
color = MainActivity.colorMap.getOrDefault(color, color);
}
// Diğer değerleri al
flashcardId = getArguments().getString("id");
category = getArguments().getString("category");
title = getArguments().getString("title");
content = getArguments().getString("content");
isFavorite = getArguments().getBoolean("favorite");
isPinned = getArguments().getBoolean("pinned");
timeStamp = getArguments().getLong("timestamp");
updatedAt = getArguments().getLong("updatedAt");
hashtags = getArguments().getStringArrayList("hashtags");
reminderTime=getArguments().getLong("reminderTime");
}
else
{
// Yeni not modunda
category = "";
title = "";
content = "";
isFavorite = false;
isPinned = false;
timeStamp = System.currentTimeMillis();
updatedAt = System.currentTimeMillis();
reminderTime = 0;
hashtags = new ArrayList<>();
backgroundColor = ""; // Varsayılan arka plan rengi
}
View view = inflater.inflate(R.layout.fragment_edit, container, false);
selectedDateTime = Calendar.getInstance();
editTextReminderTextView = view.findViewById(R.id.editTextReminderTextview);
// Görünümleri başlat.
editTextCategory = view.findViewById(R.id.editTextCategory);
editTextTitle = view.findViewById(R.id.editTextTitle);
editTextContent = view.findViewById(R.id.editTextContent);
fragmentToolbar = view.findViewById(R.id.fragmentToolbar);
fragmentBottomAppBar = view.findViewById(R.id.fragmentBottomAppBar);
textViewTimestamp = view.findViewById(R.id.textViewTimestamp);
updateViewTimestamp = view.findViewById(R.id.textViewUpdatedAt);
hashtagsEditText = view.findViewById(R.id.hashtagsEditTextView);
scrollViewLayout = view.findViewById(R.id.scrollViewContent);
// Menü'yü enflate et.
fragmentToolbar.inflateMenu(R.menu.fragment_options_menu);
// EditText ve diğer alanları doldur.
editTextCategory.setText(category);
editTextTitle.setText(title);
editTextContent.setText(content);
if(reminderTime!=0){
editTextReminderTextView.setVisibility(View.VISIBLE);
editTextReminderTextView.setText(DateFormat.getDateTimeInstance().format(reminderTime));
}
else{
editTextReminderTextView.setVisibility(View.INVISIBLE);
}
// Hashtag'ları virgülle ayrılmış şekilde EditText'e set et
if (hashtags != null && !hashtags.isEmpty()) {
String hashtagsString = TextUtils.join(", ", hashtags);
hashtagsEditText.setText(hashtagsString);
} else {
hashtagsEditText.setText("");
}
// Tarihleri formatla ve set et
Date date = new Date(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
textViewTimestamp.setText(sdf.format(date));
Date updatedDate = new Date(updatedAt);
SimpleDateFormat updatedSdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
updateViewTimestamp.setText(updatedSdf.format(updatedDate));
// Menü öğelerinin başlangıç durumunu ayarla.
initializeMenuItem(R.id.action_fav, isFavorite);
initializeMenuItem(R.id.action_pin, isPinned);
initializeMenuItem(R.id.action_alarm,reminderTime!=0);
// Menü öğeleri için tıklama dinleyicisi ayarla.
fragmentToolbar.setOnMenuItemClickListener(this::handleMenuItemClick);
// Veri değişimini takip etmek için TextWatcher ekle.
SimpleTextWatcher simpleTextWatcher = new SimpleTextWatcher(() -> isDataChanged = true);
editTextCategory.addTextChangedListener(simpleTextWatcher);
editTextTitle.addTextChangedListener(simpleTextWatcher);
editTextContent.addTextChangedListener(simpleTextWatcher);
hashtagsEditText.addTextChangedListener(simpleTextWatcher); // Hashtag EditText için ekledik.
// Eğer Not Güncelleniyorsa gelen arkaplan rengine göre not ekranı, toolbar ve bottomappbar rengini ayarla.
if(getArguments() !=null){
setNoteScreenColors(backgroundColor,fragmentToolbar,fragmentBottomAppBar);
}
return view;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
// Veri değişikliği varsa kaydet.
if (isDataChanged) {
saveChanges();
}
code
// Ana aktivitenin toolbar ve FAB'ını göster.
if (getActivity() instanceof MainActivity) {
//Not Düzenleme durumu ise
if(getArguments() !=null){
setNoteScreenColors("",fragmentToolbar,fragmentBottomAppBar);
resetDefaultScreenColors(fragmentToolbar,fragmentBottomAppBar);
}
setNoteScreenColors("",fragmentToolbar,fragmentBottomAppBar);
resetDefaultScreenColors(fragmentToolbar,fragmentBottomAppBar);
}
if (!hashtagsString.isEmpty()) {
// Hashtag'ları parse et
hashtagsList = parseHashtags(hashtagsString);
} else {
// Hashtag metin kutusu boş ise boş liste ata
hashtagsList = new ArrayList<>();
hashtagsList.add("");
}
// Kategori veya başlık yoksa varsayılan değer ata
if (category.isEmpty()) {
category = "uncategorized";
}
if (title.isEmpty()) {
title = "";
}
if (!content.isEmpty()) {
code
long alarmTime = isReminderSet ? selectedDateTime.getTimeInMillis() : 0;
//Eğer Yeni Bir Not Oluşturuluyorsa
if (getArguments() == null || flashcardId == null) {
// Yeni flashcard oluştur
String id = FirebaseManager.getInstance().getUniqueKey(); // Benzersiz bir anahtar oluşturur
String bgColor = backgroundColor != null ? backgroundColor : ""; // Seçilen veya varsayılan arka plan rengi
long timestamp = System.currentTimeMillis(); // Şu anki zaman
createFlashcard(id, category, title, content, isFavorite, isPinned, bgColor, timestamp, timestamp,alarmTime,hashtagsList);
Toast.makeText(getActivity(), "Flashcard created", Toast.LENGTH_SHORT).show();
} else {
// Geçerli reminderTime'ı tutun veya yeni seçilen zaman
alarmTime = isReminderSet ? selectedDateTime.getTimeInMillis() : reminderTime;
updateFlashcard(flashcardId, category, title, content, isFavorite, isPinned, backgroundColor, hashtagsList,alarmTime);
Toast.makeText(getActivity(), "Flashcard updated", Toast.LENGTH_SHORT).show();
}
isDataChanged = false;
} else {
Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
}
/**
Yeni bir Flashcard oluşturur
@param id Flashcard ID'si.
@param category Kategori adı.
@param title Başlık.
@param content İçerik.
@param favorite Favori durumu.
@param pinned Sabit durumu.
@param hashtags Hashtag listesi.
*/
// Yeni bir flashcard oluşturma yöntemi
private void createFlashcard(String id, String category, String title, String content, boolean favorite, boolean pinned, String backgroundColor, long timestamp, long updatedAt,long reminderTime, List hashtags) {
Flashcard flashcard = new Flashcard(id, category, title, content, favorite, pinned, backgroundColor, timestamp, updatedAt,reminderTime, hashtags);
FirebaseManager.getInstance().addFlashcard(flashcard);
}
/**
Flashcard verisini günceller.
@param id Flashcard ID'si.
@param category Kategori adı.
@param title Başlık.
@param content İçerik.
@param favorite Favori durumu.
@param pinned Sabit durumu.
@param backgroundColor Arka plan rengi.
@param hashtags Hashtag listesi.
*/
private void updateFlashcard(String id, String category, String title, String content, boolean favorite, boolean pinned, String backgroundColor, List hashtags, long reminderTime) {
Map<String, Object> updates = new HashMap<>();
updates.put("category", category);
updates.put("title", title);
updates.put("content", content);
updates.put("favorite", favorite);
updates.put("pinned", pinned);
updates.put("backgroundColor", backgroundColor); // Arka plan rengini ekle
updates.put("hashtags", hashtags); // Hashtag'ları ekliyoruz
updates.put("reminderTime",reminderTime);
long currentTimestamp = System.currentTimeMillis();
updates.put("updatedAt", currentTimestamp);
FirebaseManager.getInstance().updateFlashcard(id, updates);
}
/**
Flashcard'ı siler.
*/
private void deleteFlashcard() {
FirebaseManager.getInstance().deleteFlashcard(flashcardId);
Toast.makeText(getActivity(), "Flashcard deleted", Toast.LENGTH_SHORT).show();
// Önceki fragment'a geri dön.
requireActivity().getSupportFragmentManager().popBackStack();
}
/**
Kullanıcının girdiği hashtag stringini parse eder ve doğrular.
Her hashtag'ın '#' ile başladığından emin olur.
@param hashtagsString Kullanıcı tarafından girilen hashtag stringi.
@return Doğru formatlanmış hashtag listesi.
/
private List parseHashtags(String hashtagsString) {
List hashtagsList = new ArrayList<>();
if (!hashtagsString.isEmpty()) {
String[] splitHashtags = hashtagsString.split(",\s");
for (String tag : splitHashtags) {
if (!tag.startsWith("#")) {
tag = "#" + tag;
}
hashtagsList.add(tag);
}
}
return hashtagsList;
}
public void setNoteScreenColors(String backgroundColor, Toolbar toolbar, BottomAppBar bottomAppBar) {
// Night mode durumunu kontrol et
SharedPreferencesManager sharedPreferencesManager = new SharedPreferencesManager(getActivity());
boolean isNightModeEnabled = sharedPreferencesManager.isNightModeEnabled();
code
// Varsayılan renkleri tanımla
int defaultStatusBarColor = ContextCompat.getColor(getActivity(), R.color.navbar_color);
int defaultToolbarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
int defaultBottomAppBarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
int defaultScrollViewLayoutColor = ContextCompat.getColor(getActivity(), R.color.backgroundColor);
int defaultTextColor = ContextCompat.getColor(getActivity(), R.color.textColorPrimary);
// Arka plan rengi var mı kontrol et
int displayColor = defaultScrollViewLayoutColor;
if (backgroundColor != null && !backgroundColor.isEmpty()) {
try {
int parsedColor = Color.parseColor(backgroundColor);
if (isNightModeEnabled) {
// Gece modu için renk dönüştür
displayColor = MainActivity.reverseColorMap.getOrDefault(parsedColor, parsedColor);
} else {
// Gündüz modu için renk dönüştür
displayColor = MainActivity.colorMap.getOrDefault(parsedColor, parsedColor);
}
} catch (IllegalArgumentException e) {
// Geçersiz renk koduysa varsayılan rengi kullan
displayColor = defaultScrollViewLayoutColor;
}
}
// Arka plan rengiyle UI elementlerini güncelle
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().setStatusBarColor(displayColor);
}
if (toolbar != null) {
toolbar.setBackgroundColor(displayColor);
}
if (scrollViewLayout != null) {
scrollViewLayout.setBackgroundColor(displayColor);
}
if (bottomAppBar != null) {
bottomAppBar.setBackgroundColor(displayColor);
}
// Eğer arka plan rengi beyaz ise ve gece modundaysak, özel renklendirme yap
if (isNightModeEnabled && (backgroundColor.equalsIgnoreCase("#FFFFFF") || backgroundColor.equalsIgnoreCase("#FFFFFFFF"))) {
int whiteTextColor = ContextCompat.getColor(getActivity(), R.color.textColorPrimaryForWhiteBackgroundIssue);
setContentTextColor(whiteTextColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().setStatusBarColor(whiteTextColor);
}
if (toolbar != null) {
toolbar.setBackgroundColor(whiteTextColor);
}
if (bottomAppBar != null) {
bottomAppBar.setBackgroundColor(whiteTextColor);
}
} else {
// Varsayılan metin rengini ayarla
setContentTextColor(defaultTextColor);
}
}
// Fragment'tan çıkarken varsayılan renkleri geri yükleyin
public void resetDefaultScreenColors(Toolbar toolbar, BottomAppBar bottomAppBar) {
int defaultStatusBarColor = ContextCompat.getColor(getActivity(), R.color.navbar_color);
int defaultToolbarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
int defaultBottomAppBarColor = ContextCompat.getColor(getActivity(), R.color.primaryColor);
code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().setStatusBarColor(defaultStatusBarColor);
}
if (toolbar != null) {
toolbar.setBackgroundColor(defaultToolbarColor);
}
if (bottomAppBar != null) {
bottomAppBar.setBackgroundColor(defaultBottomAppBarColor);
}
SharedPreferencesManager sharedPreferencesManager = new SharedPreferencesManager(getActivity());
boolean isNightMode = sharedPreferencesManager.isNightModeEnabled();
final int[] colors;
if (isNightMode) {
// GoogleKeep DarkTema Not Renkleri
colors = new int[]{
R.drawable.ic_clear_color, // Rengi temizleme ikonu
0xFF232531, // Koyu mavi
0xFF482E5B, // Koyu mor
0xFF264D3B, // Koyu yeşil
0xFF274255, // Orta mavi
0xFF256476, // Açık mavi
0xFF232530, // Koyu gri
0xFF692A18, // Koyu kahverengi
0xFF76172D, // Koyu kırmızı
0xFF232428, // Koyu siyah
0xFF4B443A // Orta kahverengi
};
} else {
// GoogleKeep DayTema Not Renkleri
code
colors = new int[]{
R.drawable.ic_clear_color, // Rengi temizleme ikonu
0xFFD3D6E3, // Açık mavi
0xFFE6D9ED, // Açık mor
0xFFD9E6DD, // Açık yeşil
0xFFD9E1E6, // Orta mavi
0xFFD9E6E9, // Açık mavi
0xFFD3D6E3, // Açık gri
0xFFE6D9D3, // Açık kahverengi
0xFFE6D3D9, // Açık kırmızı
0xFFD3D6E3, // Açık siyah
0xFFE6E3D9 // Orta kahverengi
};
}
AlertDialog dialog = builder.create();
// İlk renk öğesi (renk kaldırma)
View firstColorItem = LayoutInflater.from(getActivity()).inflate(R.layout.color_item, null);
ImageView firstColorIconImgView = firstColorItem.findViewById(R.id.colorIcon);
firstColorIconImgView.setImageResource(colors[0]);
firstColorItem.setOnClickListener(v -> {
// Renk temizleme işlemi (varsayılan rengi geri yükle)
backgroundColor = ""; // Varsayılan rengi temizle
setNoteScreenColors(backgroundColor, fragmentToolbar, fragmentBottomAppBar);
dialog.dismiss();
code
// Eğer oluşturma modundaysa, sadece UI'yi günceller ve kaydetme aşamasında kullanılacak
isDataChanged = true;
});
colorGrid.addView(firstColorItem, 0);
// Diğer renkler
for (int i = 1; i < colors.length; i++) {
final int color = colors[i];
View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.color_item, null);
ImageView colorIcon = itemView.findViewById(R.id.colorIcon);
colorIcon.setBackgroundColor(color);
code
itemView.setOnClickListener(v -> {
String chosencolor = String.format("#%06X", (0xFFFFFF & color));
backgroundColor = chosencolor; // Seçilen rengi kaydet
// UI'yi güncelle
setNoteScreenColors(backgroundColor, fragmentToolbar, fragmentBottomAppBar);
dialog.dismiss();
// Oluşturma modundaysa, sadece backgroundColor değişkeni güncellenir ve saveChanges() sırasında kullanılacak
isDataChanged = true;
});
colorGrid.addView(itemView);
}
dialog.show();
}
// FragmentEdit.java içinde openLabelListFragment metodu
private void openLabelListFragment(){
FirebaseManager.getInstance().getAllLabels(new FirebaseManager.OnLabelsFetchedListener(){
@Override
public void onLabelsFetched(List allLabels){
// Mevcut notun etiketlerini alın
ArrayList currentLabels = new ArrayList<>();
if(hashtags != null){
currentLabels.addAll(hashtags);
}
code
// LabelListFragment'ı oluşturun ve benzersiz requestKey ile iletin
LabelListFragment labelListFragment = LabelListFragment.newInstance(
new ArrayList<>(allLabels),
new ArrayList<>(), // Bu senaryoda selectedFlashcardIds gerekli değilse boş bırakabilirsiniz
currentLabels,
REQUEST_KEY_UPDATE_TAGS_EDIT // Benzersiz requestKey
);
// FragmentResultListener'ı ayarlayın
getParentFragmentManager().setFragmentResultListener(
REQUEST_KEY_UPDATE_TAGS_EDIT,
getActivity(),
new FragmentResultListener(){
@Override
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result){
if (REQUEST_KEY_UPDATE_TAGS_EDIT.equals(requestKey)) {
ArrayList<String> updatedTags = result.getStringArrayList("updatedTags");
if(updatedTags != null){
// Etiketleri virgülle ayrılmış şekilde güncelleyin
String updatedTagsString = TextUtils.join(", ", updatedTags);
hashtagsEditText.setText(updatedTagsString);
hashtags = updatedTags; // Etiket listesini güncelleyin
isDataChanged = true;
Toast.makeText(getContext(), "Etiketler güncellendi.", Toast.LENGTH_SHORT).show();
}
}
}
}
);
// LabelListFragment'ı açın
getParentFragmentManager().beginTransaction()
.replace(R.id.edit_fragment_container, labelListFragment) // 'edit_fragment_container' ID'sini kullanın
.addToBackStack(null)
.commit();
}
});
}
private void showDateTimePicker() {
// Tarih seçimi için DatePickerDialog
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
(view, year, month, dayOfMonth) -> {
selectedDateTime.set(Calendar.YEAR, year);
selectedDateTime.set(Calendar.MONTH, month);
selectedDateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
code
// Saat seçimi için TimePickerDialog
TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(),
(view1, hourOfDay, minute) -> {
selectedDateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
selectedDateTime.set(Calendar.MINUTE, minute);
selectedDateTime.set(Calendar.SECOND, 0);
editTextReminderTextView.setVisibility(View.VISIBLE);
editTextReminderTextView.setText(DateFormat.getDateTimeInstance().format(selectedDateTime.getTime()));
isReminderSet = true; // Zaman seçilmişse bayrağı ayarlayın
// Alarm ikonunu erişmek
MenuItem alarmItem = fragmentToolbar.getMenu().findItem(R.id.action_alarm);
if (alarmItem != null) {
// İkonu güncelle
updateMenuIcon(alarmItem, isReminderSet);
}
},
selectedDateTime.get(Calendar.HOUR_OF_DAY),
selectedDateTime.get(Calendar.MINUTE),
false);
timePickerDialog.show();
},
selectedDateTime.get(Calendar.YEAR),
selectedDateTime.get(Calendar.MONTH),
selectedDateTime.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
}
Elbette, mevcut FragmentEdit sınıfınıza tekrarlayan hatırlatmalar eklemek için gerekli adımları detaylıca açıklayacağım. Bu süreçte:
Alarm Kurulumunu Sıklık Seçimine Göre Özelleştirmek
Bildirim Gönderimi ve Pushback (Snooze) Fonksiyonelliği Eklemek
Bu adımları uygulayarak uygulamanızda esnek hatırlatma seçenekleri sunabilirsiniz. Aşağıda, adım adım bu süreci nasıl gerçekleştirebileceğinizi anlatacağım.
İlk adım, kullanıcıların hatırlatma sıklığını seçebilecekleri bir arayüz eklemektir. En uygun seçeneklerden biri bir Spinner kullanmaktır.
a. fragment_edit.xml Dosyasını Güncelleyin
fragment_edit.xml dosyanıza bir Spinner ekleyerek kullanıcıların hatırlatma sıklığını seçmelerini sağlayabilirsiniz. Aşağıda örnek bir düzen bulunmaktadır:
xml
<!-- fragment_edit.xml içinde uygun bir yere ekleyin -->
<LinearLayout
android:id="@+id/reminderLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<!-- Varolan Hatırlatma Zamanı EditText -->
<EditText
android:id="@+id/editTextReminderTextview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Reminder Time"
android:focusable="false"
android:clickable="true"
android:inputType="none" />
<!-- Hatırlatma Sıklığı Spinner -->
<Spinner
android:id="@+id/spinnerReminderFrequency"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone" /> <!-- Başlangıçta gizli -->
</LinearLayout>
Eğer hatırlatma sıklığını yüklemek mümkünse, onCreate() içinde reminderFrequency verisini alın ve spinner'ı ayarlayın.
java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
// Mevcut kodlar...
// Hatırlatma sıklığını alın
selectedFrequency = getArguments().getString("reminderFrequency", "Tek Seferlik");
}
// Diğer kodlar...
}
3. Alarm Kurulumunu Sıklık Seçimine Göre Özelleştirmek
Hatırlatma sıklığına bağlı olarak alarm kurmak için AlarmManager kullanmanız gerekecek. Bu işlemi uygulamanın alarm kurma mantığını yöneten bir sınıfta (örneğin AlarmHelper.java) gerçekleştirmeniz önerilir. Ancak, bu sınıfın mevcut olup olmadığını bilmiyorum. Bu nedenle, temel bir AlarmHelper sınıfı oluşturacağım ve ardından hatırlatmaları kurmak için bunu nasıl kullanabileceğinizi göstereceğim.
a. AlarmHelper.java Sınıfını Oluşturun
java
// AlarmHelper.java
package com.example.newflashcard;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class AlarmHelper {
private Context context;
private AlarmManager alarmManager;
public AlarmHelper(Context context) {
this.context = context;
this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
}
public void setAlarm(String flashcardId, long triggerAtMillis, String frequency) {
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("flashcardId", flashcardId);
intent.putExtra("frequency", frequency);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, flashcardId.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
long intervalMillis = getIntervalMillis(frequency);
if (frequency.equals("Tek Seferlik")) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
} else {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, intervalMillis, pendingIntent);
}
}
public void cancelAlarm(String flashcardId) {
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, flashcardId.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
alarmManager.cancel(pendingIntent);
}
private long getIntervalMillis(String frequency) {
switch (frequency) {
case "Her 5 Dakika":
return 5 * 60 * 1000;
case "Her 10 Dakika":
return 10 * 60 * 1000;
case "Her Saat":
return AlarmManager.INTERVAL_HOUR;
case "Her 2 Saate Bir":
return 2 * AlarmManager.INTERVAL_HOUR;
case "Her Gün":
return AlarmManager.INTERVAL_DAY;
case "Her 2 Günde Bir":
return 2 * AlarmManager.INTERVAL_DAY;
case "Her Hafta":
return AlarmManager.INTERVAL_DAY * 7;
case "Hafta Sonları":
// Özel bir durumdur, yalnızca Cumartesi ve Pazar günleri
// Bu durumda tekrarlama mantığını elle kurmanız gerekecek
// Bunun için ayrı bir yöntem implement etmeniz gerekebilir
// Basitlik adına burada aynı değeri döndürüyoruz
return AlarmManager.INTERVAL_DAY * 7;
default:
return AlarmManager.INTERVAL_DAY;
}
}
}
b. AlarmReceiver.java BroadcastReceiver Sınıfını Oluşturun
Alarm tetiklendiğinde çalışacak olan BroadcastReceiver sınıfını oluşturun.
java
// AlarmReceiver.java
package com.example.newflashcard;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
public class AlarmReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "flashcard_reminder_channel";
@Override
public void onReceive(Context context, Intent intent) {
String flashcardId = intent.getStringExtra("flashcardId");
String frequency = intent.getStringExtra("frequency");
// Bildirim kanalı oluştur
createNotificationChannel(context);
// Bildirim intentini oluştur
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, flashcardId.hashCode(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
// Bildirimi oluştur
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notifications) // Uygun bir ikon ekleyin
.setContentTitle("Flashcard Hatırlatma")
.setContentText("Hatırlatmanız var!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
// Bildirimi göster
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(flashcardId.hashCode(), builder.build());
// Pushback (Snooze) işlevi eklemek isterseniz, burada bir eylem butonu ekleyebilirsiniz
// Eğer belirli bir sıklık için tekrarlama gerekiyorsa, alarmı tekrar kurabilirsiniz
AlarmHelper alarmHelper = new AlarmHelper(context);
if (!frequency.equals("Tek Seferlik")) {
// Gelecek alarm kurulumu burada yapılabilir
// Ancak zaten setRepeating kullanıldığından tekrar kurmaya gerek yok olabilir
}
}
private void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Flashcard Reminders";
String description = "Notification channel for flashcard reminders";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
c. AndroidManifest.xml Dosyasına Receiver'ı Ekleyin
d. Alarm Kurulumunu FragmentEdit.java İçinden Gerçekleştirin
saveChanges metodunda, alarmın kurulması veya iptal edilmesi işlemlerini gerçekleştirin.
i. Alarm'ın Kurulması veya İptal Edilmesi
java
private void saveChanges() {
category = editTextCategory.getText().toString().trim();
title = editTextTitle.getText().toString().trim();
content = editTextContent.getText().toString().trim();
String hashtagsString = hashtagsEditText.getText().toString().trim();
List<String> hashtagsList;
if (!hashtagsString.isEmpty()) {
hashtagsList = parseHashtags(hashtagsString);
} else {
hashtagsList = new ArrayList<>();
hashtagsList.add("");
}
if (category.isEmpty()) {
category = "uncategorized";
}
if (title.isEmpty()) {
title = "";
}
if (!content.isEmpty()) {
long alarmTime = isReminderSet ? selectedDateTime.getTimeInMillis() : 0;
String reminderFrequency = selectedFrequency;
AlarmHelper alarmHelper = new AlarmHelper(getActivity());
if (getArguments() == null || flashcardId == null) {
// Yeni flashcard oluştur
String id = FirebaseManager.getInstance().getUniqueKey();
String bgColor = backgroundColor != null ? backgroundColor : "";
long timestamp = System.currentTimeMillis();
createFlashcard(id, category, title, content, isFavorite, isPinned, bgColor, timestamp, timestamp, alarmTime, reminderFrequency, hashtagsList);
Toast.makeText(getActivity(), "Flashcard created", Toast.LENGTH_SHORT).show();
// Alarm'ı kur
if (isReminderSet) {
alarmHelper.setAlarm(id, alarmTime, reminderFrequency);
}
} else {
// Var olan flashcard'ı güncelle
updateFlashcard(flashcardId, category, title, content, isFavorite, isPinned, backgroundColor, hashtags, alarmTime, reminderFrequency);
Toast.makeText(getActivity(), "Flashcard updated", Toast.LENGTH_SHORT).show();
// Alarm'ı güncelle
if (isReminderSet) {
alarmHelper.setAlarm(flashcardId, alarmTime, reminderFrequency);
} else {
// Hatırlatma kaldırıldıysa alarm'ı iptal et
alarmHelper.cancelAlarm(flashcardId);
}
}
isDataChanged = false;
} else {
Toast.makeText(getActivity(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
}
4. Bildirim Gönderimi ve Pushback (Snooze) Fonksiyonelliği Eklemek
Kullanıcının bildirim geldiğinde "Pushback" (Snooze) yapabilmesi için bildirimlere eylem butonları ekleyebiliriz. Bunun için AlarmReceiver sınıfını güncelleyelim.
a. AlarmReceiver.java İçinde Pushback Eylemi Ekleyin
b. SnoozeReceiver.java BroadcastReceiver Sınıfını Oluşturun
Pushback (Snooze) işlemi için bir BroadcastReceiver oluşturun.
java
// SnoozeReceiver.java
package com.example.newflashcard;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class SnoozeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String flashcardId = intent.getStringExtra("flashcardId");
String frequency = intent.getStringExtra("frequency");
// Pushback işlemi: Alarmı 5 dakika sonra tekrar kur
AlarmHelper alarmHelper = new AlarmHelper(context);
long newAlarmTime = System.currentTimeMillis() + 5 * 60 * 1000; // 5 dakika sonra
alarmHelper.setAlarm(flashcardId, newAlarmTime, frequency);
// Kullanıcıya Toast bildirimi gönder
Toast.makeText(context, "Pushback (Snooze) işlemi gerçekleştirildi.", Toast.LENGTH_SHORT).show();
}
}
c. AndroidManifest.xml Dosyasına SnoozeReceiver'ı Ekleyin
xml
<receiver android:name=".SnoozeReceiver" />
Son Adımlar
Yukarıdaki adımlarla birlikte, kullanıcılar hatırlatma sıklığını seçebilecek ve seçilen sıklığa göre hatırlatmalar kurulacaktır. Ayrıca, aldıkları bildirimlerde "Pushback" (Snooze) butonunu kullanarak hatırlatmayı 5 dakika sonra tekrar alabilirler.
Notlar:
Hafta Sonları Sıklığı:Hafta Sonları gibi özel sıklıklar için daha karmaşık bir alarm mantığı gerekebilir. Bu durumda, belirli günlerde alarm kurmak için tekrarlayan alarm kurulumunu özelleştirebilirsiniz. Örneğin, Cumartesi ve Pazar günleri wieder kurmak için ayrı ayrı alarm kurabilirsiniz.
Battery Optimize: AlarmManager kullanırken cihazın batarya optimizasyonunu dikkate alın. setExactAndAllowWhileIdle kullanarak alarmları daha tutarlı kurabilirsiniz, ancak bu daha fazla enerji tüketebilir.
İzinler: Uygulamanızın bildirim gönderebilmesi için gerekli izinlere sahip olduğundan emin olun. Genellikle, AndroidManifest.xml dosyanıza aşağıdaki izni eklemeniz yeterlidir:
Ayrıca, cihaz yeniden başlatıldığında alarmları tekrar kurmak için BootReceiver gibi bir BroadcastReceiver eklemeyi düşünebilirsiniz.
Kullanıcı Deneyimi: Kullanıcıların hatırlatmaları kolaylıkla ayarlayabilmesi için arayüzü kullanıcı dostu hale getirmeniz önemlidir. Sıklık seçeneklerini daha anlaşılır ve erişilebilir hale getirmek için ikonlar veya açıklamalar eklemeyi düşünebilirsiniz.
Test Etme: Alarmların ve bildirimlerin doğru çalıştığından emin olmak için uygulamanızı farklı durumlarda (farklı sıklıklar, cihaz yeniden başlatma, uygulama kapalıyken vs.) test edin.
Bu adımları takip ederek uygulamanızda esnek ve kullanıcı dostu hatırlatma seçenekleri sunabilirsiniz. Herhangi bir sorunuz olursa veya ek yardıma ihtiyaç duyarsanız, lütfen sormaktan çekinmeyin!