Как правильно настроить Notification в андроид проекте?
У меня имеется небольшое приложение, которое выполняет роль Task Manager'a. Попробовал настроить уведомление по конкретной дате (то есть выставляю дату через DataPickerDialog) и хотелось бы чтобы приходило уведомление в назначенный день, чего собственно не происходит. Прошу помочь разобраться в проблеме
NoteActivity:
public class NoteActivity extends AppCompatActivity {
private static final String EXTRA_NOTE = "NoteActivity.EXTRA_NOTE";
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
final Calendar myCalendar = Calendar. getInstance () ;
private Note note;
private EditText etTitle;
private EditText etDesc;
private TextView tvDateOfCreate;
private Button btnDate;
int DIALOG_DATE = 1;
int myYear = 2021;
int myMonth = 1;
int myDay = 1;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm, dd-MM-yyyy");
public static void start(Activity caller, Note note) {
Intent intent = new Intent (caller, NoteActivity.class);
if (note != null) {
intent.putExtra(EXTRA_NOTE, note);
}
caller.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
Toolbar toolbar = findViewById(R.id.toolbarNote);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
setTitle(getString(R.string.note_create));
etTitle = findViewById(R.id.etTitle);
etDesc = findViewById(R.id.etDesc);
tvDateOfCreate = findViewById(R.id.tvDateOfCreateNote);
btnDate = findViewById(R.id.btnDate);
if (getIntent().hasExtra(EXTRA_NOTE)) {
note = getIntent().getParcelableExtra(EXTRA_NOTE);
btnDate.setVisibility(View.INVISIBLE);
etTitle.setText(note.title);
etDesc.setText(note.text);
tvDateOfCreate.setText("Дата создания заметки: " + note.date);
tvDateOfCreate.setVisibility(View.VISIBLE);
} else {
note = new Note();
}
}
private void scheduleNotification (Notification notification , long delay) {
Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ;
notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ;
notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ;
PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 ,
notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ;
AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ;
assert alarmManager != null;
alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , delay , pendingIntent) ;
}
private Notification getNotification (String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder( this,
default_notification_channel_id ) ;
builder.setContentTitle( "Scheduled Notification" ) ;
builder.setContentText(content) ;
builder.setSmallIcon(R.mipmap.ic_launcher ) ;
builder.setAutoCancel( true ) ;
builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
return builder.build() ;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_note, menu);
return super.onCreateOptionsMenu(menu);
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.action_save:
if ((etDesc.getText().length() > 0) && (etTitle.getText().length() > 0)) {
note.title = etTitle.getText().toString();
note.text = etDesc.getText().toString();
note.done = false;
note.plannedDay = btnDate.getText().toString();
note.date = sdf.format(Calendar.getInstance().getTime());
note.timestamp = System.currentTimeMillis();
if (getIntent().hasExtra(EXTRA_NOTE)) {
App.getInstance().getNoteDao().update(note);
} else {
App.getInstance().getNoteDao().insert(note);
}
finish();
} else {
Toast.makeText(this, "Заполните поля названия и описания заметки",
Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
public void onChangeDate(View view) {
showDialog(DIALOG_DATE);
}
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_DATE) {
DatePickerDialog tpd = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
return tpd;
}
return super.onCreateDialog(id);
}
DatePickerDialog.OnDateSetListener myCallBack = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myYear = year;
myMonth = monthOfYear;
myDay = dayOfMonth;
btnDate.setText("Задана дата " + myDay + "/" + myMonth + "/" + myYear);
myCalendar.set(Calendar. YEAR , year) ;
myCalendar.set(Calendar. MONTH , monthOfYear) ;
myCalendar.set(Calendar. DAY_OF_MONTH , dayOfMonth) ;
updateLabel();
}
};
private void updateLabel () {
Date date = myCalendar.getTime();
scheduleNotification(getNotification(btnDate.getText().toString()) , date.getTime()) ;
}
}
NotificationPublisher:
public class MyNotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id" ;
public static String NOTIFICATION = "notification" ;
public void onReceive (Context context , Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ;
Notification notification = intent.getParcelableExtra( NOTIFICATION ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel) ;
}
int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ;
assert notificationManager != null;
notificationManager.notify(id , notification) ;
}
}
Уже думал, может как то через Firebase (FCM) организовать, но не знаю, как это правильно сделать.