Android Studio - Как запланировать уведомление?Android

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Android Studio - Как запланировать уведомление?

Сообщение Anonymous »

Я создал образец уведомления о проекте, над которым я сейчас работаю, используя этот код в методе oncreate < /strong> моего основного действия.
Я также получил Timepicker
Fragment Class, который, как следует из названия, открывает диалог Sicker Time, который позволяет пользователю установить определенное время суток. Затем, час и минуты хранятся в DataSite.class , который содержит ряд методов GET и установления. Ниже приведен код для Timepicker.class :
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
DataSite ds = new DataSite();
ds.setHour(hourOfDay);
ds.setMinute(minute);
}
}

Короче говоря, я хотел бы запланировать CreateNotificationChannel (); вызов метода на основную деятельность в соответствии с Hour и Протокол пользователь выбрал. Как я уже сказал, информация о времени хранится в DataSite . Все, что мне нужно сейчас, - это способ объединить эти две функции. Насколько я могу судить из других сообщений на форуме, мне придется использовать Manager сигнал тревоги , но ничего, что я прочитал в другом месте, не работает для меня.
РЕДАКТИРОВАТЬ: Я попытался использовать AlarmManager . Ниже вы можете увидеть полный код, который у меня есть в настоящее время:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial_screen);
.
.
.
.
.
Intent intent = new Intent(this, InitialScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "reflectnotification")
.setSmallIcon(R.drawable.app_icon_background)
.setContentTitle("Reflect Reminder")
.setContentText("Time to Reflect on your selected Goal!")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Time to Reflect on your selected Goal!"))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
createNotificationChannel();
// notificationManager.notify(200, builder.build());

hour = ((DataSite)getApplication()).getHour();
minute = ((DataSite)getApplication()).getMinute();

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);

Toast.makeText(getApplicationContext(),"Picked time: "+ hour +":"+minute, Toast.LENGTH_LONG).show();

alarmMgr = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent2 = new Intent(getApplicationContext(), InitialScreen.class);
alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 200, intent2, 0);

alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
< /code>
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Reflect Reminder";
String description = "Time to Reflect on your selected Goal!";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("reflectnotification", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}


Подробнее здесь: https://stackoverflow.com/questions/714 ... tification
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»