Adapting to notifications

1

Based on some answers found in this site I adapted a code to get notifications at a certain time if someone can finalize this code and help me to activate the notifications

Screen on which to call the notification:

public class EscolhaLuzCasa extends AppCompatActivity {
    private EditText rep1, rep2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_escolha_luz_casa);

        rep1 = (EditText) findViewById(R.id.horarep1);
        rep2 = (EditText) findViewById(R.id.rep2);
    }

    public void onClick(View view ) {
        Context context = null;

        StartUpBootReceiver.setAlarm(context , 21, 30);
        int valor = (Integer.parseInt(rep1.getText().toString()));

            if(valor >= 300) {
                Intent intent = new Intent(this, luzcasaalto.class);
                startActivity(intent);
            }else if (valor <= 200  &&  (valor  >= 100)){
                Intent intent = new Intent(this, luzcasamedio.class);
                startActivity(intent);
            }else if (valor < 100 ){
            Intent intent = new Intent(this, luzcasabaixo.class);
            startActivity(intent);

        }
    }
}

StartUpBootReceiver :

public class StartUpBootReceiver extends BroadcastReceiver {

    private static int REPEATING_ID = 1001;
    private static int ON_TIME_ID = 1002;
    private static String HOUR = "hour";
    private static String MINUTE = "minute";


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


    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            setAlarm(context);
            Toast.makeText(context, "Alarm set", 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;
        }
        //Cancela possiveis alarmes existentes
        cancelAlarm(context);

        Calendar calendar = getCalendar(hour, minute);

        //Se já passou
        if(isDateBeforeNow(calendar)){
            //adiciona um dia
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }else{
            //Alarme para o horário especificado
            setOneTimeAlarm(context, calendar);
            //adiciona um dia para repetir o alarme no dia seguinte
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        //Repete o alarme no dia seguinte
        setRepeatingAlarm(context, calendar);
    }

    private static void setRepeatingAlarm(Context context, Calendar calendar){
        PendingIntent pendingIntent = getPendingIntent(context, REPEATING_ID);

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

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

    private static void setOneTimeAlarm(Context context, Calendar calendar){
        PendingIntent pendingIntent= getPendingIntent(context, ON_TIME_ID);

        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

        //Alarme para o horário especificado
        alarmManager.set(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                pendingIntent);
    }

    private static void cancelAlarm(Context context){
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(getPendingIntent(context, ON_TIME_ID));
        alarmManager.cancel(getPendingIntent(context, REPEATING_ID));
    }

    private static PendingIntent getPendingIntent(Context context, int id){
        //PendingIntent para lançar o serviço
        Intent serviceIntent = new Intent(context, BootService.class);
        return PendingIntent.getService(context, id, serviceIntent, 0);
    }

    private static Calendar getCalendar(int hour, int minute){
        // Cria um Calendar para o horário especificado
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

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

BootService :

public class BootService  extends IntentService {

    private PowerManager.WakeLock wakeLock;

    public BootService() {
        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, "BootService");
        wakeLock.acquire();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "S")
                .setSmallIcon(R.drawable.casa)
                .setContentTitle("leklek")
                .setContentText("PARABENSSSSS CARALHOOOOOOOOOOO")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    }

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

Manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.aleander.ma_e">
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <application
        android:name=".aguacasatodosmetodos.crud.crud.Myapp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service android:name=".luzcasatodosmetodos.BootService"/>
        <receiver android:name=".luzcasatodosmetodos.StartUpBootReceiver">    </receiver>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Agua" />
        <activity android:name=".Luz" />
        <activity android:name=".aguaempresatodosmetodos.EscolhaAguaEmpresa" />
        <activity android:name=".aguacasatodosmetodos.crud.EscolhaAguaCasa" />
        <activity android:name=".luzcasatodosmetodos.EscolhaLuzCasa" />
        <activity android:name=".luzempresatodosmetodos.EscolhaLuzEmpresa" />
        <activity android:name=".aguacasatodosmetodos.crud.aguacasa.alto" />
        <activity android:name=".aguacasatodosmetodos.crud.aguacasa.medio" />
        <activity android:name=".aguacasatodosmetodos.crud.aguacasa.baixo" />
        <activity android:name=".aguaempresatodosmetodos.aguaempresa.medioaguaempresa" />
        <activity android:name=".aguaempresatodosmetodos.aguaempresa.baixoaguaempresa" />
        <activity android:name=".aguaempresatodosmetodos.aguaempresa.altoaguaempresa" />
        <activity android:name=".luzcasatodosmetodos.luzcasa.luzcasaalto" />
        <activity android:name=".luzcasatodosmetodos.luzcasa.luzcasabaixo" />
        <activity android:name=".luzcasatodosmetodos.luzcasa.luzcasamedio" />
        <activity android:name=".luzempresatodosmetodos.luzempresa.luzempresaalto" />
        <activity android:name=".luzempresatodosmetodos.luzempresa.luzempresamedio" />
        <activity android:name=".luzempresatodosmetodos.luzempresa.luzempresabaixo" />
    </application>
</manifest>
    
asked by anonymous 07.06.2018 / 01:45

0 answers