2
I am taking a test before implementing in the real application. I have an application with two buttons (Date and Time) and a button (Schedule). As soon as the user clicks on the Date button, a Datepicker opens to choose the date. Same time, open a Timepicker so he can pick the time. The date and time go to an Edittext for the user to view and so be able to tap the Schedule button.
I can’t seem to get the Schedule into Alarmmanager. If I set only the date works, but if I set the date and time, the notification already displayed soon after.
Códido Main
    public class MainActivity extends AppCompatActivity {
    private EditText dataEscolhida;
    private EditText materia;
    private EditText horarioEscolhido;
    private Button calendarioData;
    private Button horarioAgendado;
    private Button botaoAgendar;
    SimpleDateFormat formatarData = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat formatarHora = new SimpleDateFormat("HH:mm", Locale.getDefault());
    Calendar calendar = Calendar.getInstance();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dataEscolhida = (EditText) findViewById(R.id.edt_dataEscolhida);
        materia = (EditText) findViewById(R.id.edt_materia);
        botaoAgendar = (Button) findViewById(R.id.btn_agendarNotificacao);
        calendarioData = (Button) findViewById(R.id.btn_calendárioDatePicker);
        horarioAgendado = (Button) findViewById(R.id.btn_horario);
        horarioEscolhido = (EditText) findViewById(R.id.edt_horario);
        botaoAgendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String dataAgendada = dataEscolhida.getText().toString();
                Log.d("Data agendada", String.valueOf(dataAgendada));
                String materiaAgendada = materia.getText().toString();
                agendarNotificacao(getNotification(materiaAgendada), calendar.getTime());
                Log.d("Agendamento", "Agendou");
            }
        });
        calendarioData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atualizarData();
            }
        });
        horarioAgendado.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atualizaHorario();
            }
        });
    }
    private void exibeDataNoCampo() {
        dataEscolhida.setText(formatarData.format(calendar.getTime()));
        Log.d("Data escolhida: ", String.valueOf(dataEscolhida));
    }
    private void exibeHorarioNoCampo() {
        horarioEscolhido.setText(formatarHora.format(calendar.getTime()));
        Log.d("Hora escolhida: ", String.valueOf(horarioEscolhido));
    }
    private void atualizarData() {
        new DatePickerDialog(this, data, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
//Salva a data que o usuário configurou
    DatePickerDialog.OnDateSetListener data = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            exibeDataNoCampo();
        }
    };
    private void atualizaHorario() {
        new TimePickerDialog(this, horario, calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), true).show();
    }
//Salva o horário que o usuário configurou
    TimePickerDialog.OnTimeSetListener horario = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            exibeHorarioNoCampo();
        }
    };
    @TargetApi(Build.VERSION_CODES.N)
    private void agendarNotificacao(Notification notification, Date dataAgendada) {
        Intent intentNotificacao = new Intent(this, Notificacao.class);
        calendar.setTime(dataAgendada);
        //Irá gerar as id aleatorias para cada notificação
        int id = (int) (Math.random() * 1000);
        intentNotificacao.putExtra(Notificacao.NOTIFICATION_ID, id);
        intentNotificacao.putExtra(Notificacao.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intentNotificacao,
                PendingIntent.FLAG_UPDATE_CURRENT);
        // long tempodedisparo =  calendar.getTimeInMillis() + segundosAgendado * 60000 ;
        //disparo de notificacao
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                pendingIntent);
        Log.d("AgendarNOtificacao", "agendarnotificacao");
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private Notification getNotification(String content) {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("Lembrete: Estudar a matéria");
        builder.setContentText(content);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        Log.d("Construindo Notificacao", "Construindo Notificacao");
        return builder.build();
    }
}
My Class of Broadcast
public class Notificacao extends BroadcastReceiver {
    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification);
        //som da mensagem
        try {
            Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone toque = RingtoneManager.getRingtone(context, som);
            toque.play();
        }catch (Exception e){e.printStackTrace(); }
        Log.d("Notificação Exibida", "Notificacao Exibida");
    }
}
My XML
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="notificacaocomalarmmanager.com.flaviodeoliveira.notificacaocomalarmmanager.MainActivity">
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:ems="10"
        android:id="@+id/edt_materia"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:hint="Qual materia?"/>
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:ems="10"
        android:id="@+id/edt_dataEscolhida"
        android:hint="Data?"
        android:layout_below="@+id/edt_materia"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp" />
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Agendar Notificação"
        android:id="@+id/btn_agendarNotificacao"
        android:layout_below="@+id/btn_horario"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calendario"
        android:id="@+id/btn_calendárioDatePicker"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edt_horario"
        android:hint="Horário"
        android:layout_below="@+id/edt_dataEscolhida"
        android:layout_centerHorizontal="true" />
    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Horário"
        android:id="@+id/btn_horario"
        android:layout_below="@+id/btn_calendárioDatePicker"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
						
within the Gendar method, I changed the
String dataAgendada = dataEscolhida.getText().toString();>>> Here I am getting the dateDate dataAgendada = (Date) dataEscolha.getText();agendarNotificacao(getNotification(materiaAgendada), dataAgendada);But error appears in Logcatjava.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to java.util.DateOdataAgendaI’m also passing theprivate void agendarNotificacao(Notification notification, Date dataAgendada)– Flávio
You have to convert your string to Date format.
– viana