Skip to main content
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
tags editadas; tags editadas; tags editadas
Link
ramaral
  • 44,7mil
  • 14
  • 60
  • 110
adicionou 1076 caracteres ao conteúdo
Fonte Link
Flávio
  • 323
  • 3
  • 15

Minha classe de 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");
    }
}

Minha classe de 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");
    }
}
Fonte Link
Flávio
  • 323
  • 3
  • 15

Configurar horário específico no AlarmManager pelo TimePicker e DatePicker

estou fazendo um teste ainda antes de implementar no aplicativo real. Tenho um aplicação com dois botões (Data e Horário) e um botão (Agendar). Assim que usuário clica no botão Data, abre um DatePicker para ele escolher a data. No horário é a mesma coisa, abre um TimePicker para que ele escolha o horário. A data e hora vão para um EditText para o usuário possa visualizar e assim poder tocar no botão Agendar.

Não estou conseguindo colocar o Horário no AlarmManager. Se eu configurar apenas a data funciona, mas se eu configurar a data e horário, a notificação já exibida logo em seguida.

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();

    }

}

Meu 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>