Notices at random times is possible?

0

I am using BroadcastReceiver along with alarmmaneger to send notifications and among these I thought about sending a notification between the hours of 12 the 19 randomly like if today sent the 12 hours and amanaha the 16 so that I could not think of a way to do so if anyone knows how to deploy it the way I'm doing, I'll leave my code here. Thanks!

BroadcastReceiver

public class PrimeiraNotiAguaCasa extends BroadcastReceiver {

    private static String HOUR = "hour";
    private static String MINUTE = "minute";
public static int a ;
public  static int b ;




    public static void setAlarm(Context context, int hour, int minute){

        SharedPreferences preferences =  PreferenceManager.getDefaultSharedPreferences(context);
        preferences.edit()
                .putInt(HOUR, hour)
                .putInt(MINUTE, minute)
                .apply();
        setAlarm(context);
        a = hour;
        b = minute;

    }



    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent pushIntent = new Intent(context, TestService.class);
            context.startService(pushIntent);
            setAlarm(context);
            Toast.makeText(context, "Alarm set" + a +"minu" + b, Toast.LENGTH_LONG).show();
        }
    }




    private static void setAlarm(Context context) {

        int hour = getHour(context);
        int minute = getMinute(context);

        if(hour == -1 || minute == -1){
            //nenhum horário definido
            return;
        }

        // Cria um Calendar para o horário estipulado
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);

        //Se já passou
        if(isDateBeforeNow(calendar)){
            //adiciona um dia
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }


        //PendingIntent para lançar o serviço
        Intent serviceIntent = new Intent(context, BootServicePrimeiraAguaCasa.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, serviceIntent, 0);

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        //Cancela um possível alarme existente
        alarmManager.cancel(pendingIntent);

        //Alarme que se repete todos os dias a uma determinada hora
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY,
                pendingIntent);

    }

    private static int getHour(Context context){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getInt(HOUR, -1);
    }
    private static int getMinute(Context context){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getInt(MINUTE, -1);
    }

    private static boolean isDateBeforeNow(Calendar calendar){
        return calendar.getTimeInMillis() <= System.currentTimeMillis();
    }

    }

IntentService

public class BootServicePrimeiraAguaCasa  extends IntentService {


    private PowerManager.WakeLock wakeLock;

    public BootServicePrimeiraAguaCasa() {
        super("name");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.ON_AFTER_RELEASE, "BootServicePrimeiroLuzCasa");
        wakeLock.acquire();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {


        List<String> opcoes = Arrays.asList("Evite apagar e acender a luz o tempo todo. O consumo maior das lâmpadas fluorescentes está no ato de acender.", "Não esqueça as luzes ligadas. ", "Use papéis usados para rascunho"
        );
        CharSequence selecionada = opcoes.get(new Random().nextInt(opcoes.size()));


        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.icone)
                .setContentTitle("Voce sabia?")
                .setContentText(selecionada);

        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(selecionada))
                .setAutoCancel(true);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, builder.build());


    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (wakeLock.isHeld()) {
            //Verificou-se que o iluminar do ecrã
            //não acontecia devido ao WakeLock ser
            //rapidamente libertado(apesar de PowerManager.ON_AFTER_RELEASE !?).
            try {
                //Atrasa a libertação do WakeLock
                //de forma a permitir a iluminação do ecrâ.
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                wakeLock.release();
            }
        }
}}

How do I call SetAlarm to randomly pick up the schedule?

 opcoes = new ArrayList<>();
    int inicial = EscolhaAguaCasa.ho1;
    int total = EscolhaAguaCasa.ho2;
    for (int i = inicial+1; i < total; i++) {
        Toast.makeText(this, "hora" + i, Toast.LENGTH_SHORT).show();
        opcoes.add(i);
    }
    opcoes.add(EscolhaAguaCasa.ho1);
    opcoes.add(EscolhaAguaCasa.ho2);


    opcoesminu = new ArrayList<>();
    int iniciall = EscolhaAguaCasa.mi1;
    int totall = EscolhaAguaCasa.mi2;
    for (int i = iniciall+1; i < totall; i++) {
        Toast.makeText(this, "minu" + i, Toast.LENGTH_SHORT).show();
        opcoesminu.add(i);



    }

    Integer selecionadaa = opcoes.get(new Random().nextInt(opcoesminu.size()));
    Integer selecionada = opcoes.get(new Random().nextInt(opcoes.size()));

    PrimeiraNotiAguaCasa.setAlarm(this , selecionada , selecionadaa );
    
asked by anonymous 21.07.2018 / 19:16

0 answers