Set specific time in AlarmManager by TimePicker and DatePicker

1

I'm doing a test before implementing the actual application. I have a two-button application (Date and Time) and a button (Schedule). As soon as the user clicks the Date button, it opens a DatePicker so that it chooses the date. On time it's the same thing, open a TimePicker so he can choose the time. The date and time go to an EditText for the user to view so that he can touch the Schedule button.

I can not put the Time in AlarmManager. If I configure only the date works, but if I set the date and time, the notification already displayed soon thereafter.

Main Code

    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 Broadcast Class

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>
    
asked by anonymous 27.05.2017 / 16:36

1 answer

0
  

[...] the notification already displayed shortly ...

That's because you're really setting it so it will be displayed right away. When you click botaoAgendar , you are passing the current time, using calendar.getTime() , to set the alarm, when in fact it should be the time set in EditText .

To fix, just pass as a parameter the correct time set in TimePicker and DatePicker , in which you want the notification to appear in agendarNotificacao() method

    
27.05.2017 / 17:38