#android #android-notifications
Вопрос:
Я попытался добавить опцию выбора определенного времени и даты для уведомления в пользовательском интерфейсе. Сначала это работало нормально, когда время было задано в коде, а не пользователями. Мои уведомления перестали появляться с тех пор, как я это изменил, и я не знаю, что происходит.
Функция в главном меню, которая синхронизирует уведомления:
private void syncNotifications() {
FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("notifications")
.whereEqualTo("ownerID", FirebaseAuth.getInstance().getCurrentUser().getUid())
.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
List<Notification> items = value.toObjects(Notification.class);
AlarmManager manager = (AlarmManager)(getSystemService( Context.ALARM_SERVICE ));
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy",new Locale("pl","PL"));
//SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
try {
long time = 0;
for (Notification notification : items) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateFormat.parse(notification.getDate()));
String[] timeFormatParser = notification.getTime().split( ":" );
int hour = Integer.parseInt ( timeFormatParser[0].trim() );
int min = Integer.parseInt ( timeFormatParser[1].trim() );
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, min);
if(calendar.getTimeInMillis() >= System.currentTimeMillis()) {
time = 10000;
Intent serviceIntent = new Intent(getBaseContext(), NotificationService.class);
serviceIntent.putExtra("petName", notification.getPetName());
serviceIntent.putExtra("message", notification.getText());
PendingIntent intent = PendingIntent.getBroadcast(getBaseContext(), new Random().nextInt(), serviceIntent, 0);
manager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() time, intent);
}
}
}
catch(Throwable e){
}
}
});
}
Служба уведомлений:
package com.example.petcare;
import android.app.Notification;
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.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import java.util.Random;
public class NotificationService extends BroadcastReceiver {
public NotificationManager myNotificationManager;
public static final int NOTIFICATION_ID = 1;
@Override
public void onReceive(Context context, Intent intent) {
myNotificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( "channelID", "NOTIFICATION_CHANNEL_NAME" , importance) ;
myNotificationManager.createNotificationChannel(notificationChannel) ;
}
Intent notificationIntent = new Intent(context, eventsActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
CharSequence NotificationTicket = "Notif";
NotificationCompat.Builder builder = new NotificationCompat.Builder(context , "channelID" ) ;
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle(intent.getStringExtra("petName"));
builder.setContentText(intent.getStringExtra("message"));
builder.setContentIntent(contentIntent);
myNotificationManager.notify(new Random().nextInt(), builder.build());
}
}
Notification activity:
package com.example.petcare;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import com.example.petcare.db.Notification;
import com.example.petcare.db.Pet;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class notificationActivity extends AppCompatActivity {
private FirebaseFirestore firebaseFirestore;
private EditText textInput;
private Button selectDateButton;
private Button selectTimeButton;
private Button addBt;
private Pet pet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_notification);
firebaseFirestore = FirebaseFirestore.getInstance();
textInput =(EditText) findViewById(R.id.addingTextNotification);
selectDateButton =(Button) findViewById(R.id.selectDateBt);
selectTimeButton =(Button) findViewById(R.id.selectTimeBt);
addBt = (Button) findViewById(R.id.saveNotificationBt);
String notificationID = getIntent().getStringExtra("notificationID");
String petID = getIntent().getStringExtra("petID");
if (petID != null){
getPetName(petID);
}
selectTimeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(notificationActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
selectTimeButton.setText(hourOfDay ":" minute);
/* if(hourOfDay >= 0 amp;amp; hourOfDay <= 9)
selectTimeButton.setText("0" hourOfDay ":" minute);
if(minute >= 0 amp;amp; minute <= 9)
selectTimeButton.setText(hourOfDay ":" "0" minute); */
}
}, mHour, mMinute, true);
timePickerDialog.show();
}
});
selectDateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar myCalendar = Calendar.getInstance();
new DatePickerDialog(notificationActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, month);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat dateFormat= new SimpleDateFormat("dd-MM-yyyy", new Locale("pl","PL"));
selectDateButton.setText(dateFormat.format(myCalendar.getTime()));
}
}, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
if(notificationID == null)
{
addBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = textInput.getText().toString();
String date = selectDateButton.getText().toString();
String time = selectTimeButton.getText().toString();
if(text.length()>0 amp;amp; date.length()>0 amp;amp; time.length()>0)
{
addNotification(textInput.getText().toString(), selectDateButton.getText().toString(), selectTimeButton.getText().toString(), petID);
}
else
{
}
}
});
}
else
{
firebaseFirestore.collection("notifications").document(notificationID).addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
Notification notification = value.toObject(Notification.class);
textInput.setText(notification.getText());
selectDateButton.setText(notification.getDate());
selectTimeButton.setText(notification.getTime());
addBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = textInput.getText().toString();
String date = selectDateButton.getText().toString();
String time = selectTimeButton.getText().toString();
if(text.length()>0 amp;amp; date.length()>0 amp;amp; time.length()>0)
{
updateNotification(text, date, time, notification.getId(), notification.getPetID());
}
else
{
}
}
});
}
});
}
}
private void getNotificationDetails(String notificationID) {
firebaseFirestore.collection("notifications").document(notificationID)
.get().addOnCompleteListener(this, new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
Notification notification = task.getResult().toObject(Notification.class);
fillUI(notification);
}
});
}
private void fillUI(Notification notification) {
textInput.setText(notification.getText());
selectDateButton.setText(notification.getDate());
}
private void getPetName(String petID) {
firebaseFirestore.collection("pets").document(petID)
.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
pet = value.toObject(Pet.class);
}
});
}
private void updateNotification(String text, String date, String time, String notificationID, String petID) {
firebaseFirestore.collection("notifications").document(notificationID)
.set(new Notification(
notificationID,
petID,
text,
date,
time, FirebaseAuth.getInstance().getCurrentUser().getUid(),
pet.getName()))
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
finish();
}
});
}
private void addNotification(String text, String date, String time, String petID) {
DocumentReference doc = firebaseFirestore.collection("notifications").document();
doc.set(new Notification(
doc.getId(),
petID,
text,
date,
time, FirebaseAuth.getInstance().getCurrentUser().getUid(),
pet.getName()))
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
finish();
}
});
}
}