Skip to content

Instantly share code, notes, and snippets.

@rafaeltoledo
Last active November 5, 2019 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaeltoledo/cbfdad49a65dd39275c3b51850a0eb20 to your computer and use it in GitHub Desktop.
Save rafaeltoledo/cbfdad49a65dd39275c3b51850a0eb20 to your computer and use it in GitHub Desktop.
Android 20
package net.rafaeltoledo.restaurante;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
public class PreferenciaHorario extends DialogPreference {
private int ultimaHora = 0;
private int ultimoMinuto = 0;
private TimePicker picker = null;
public static int obterHora(String tempo) {
String[] fragmentos = tempo.split(":");
return Integer.parseInt(fragmentos[0]);
}
public static int obterMinuto(String tempo) {
String[] fragmentos = tempo.split(":");
return Integer.parseInt(fragmentos[1]);
}
public PreferenciaHorario(Context contexto) {
this(contexto, null);
}
public PreferenciaHorario(Context contexto, AttributeSet atributos) {
this(contexto, atributos, 0);
}
public PreferenciaHorario(Context contexto, AttributeSet atributos, int estilo) {
super(contexto, atributos, estilo);
setPositiveButtonText("Definir");
setNegativeButtonText("Cancelar");
}
@Override
protected View onCreateDialogView() {
picker = new TimePicker(getContext());
return picker;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
picker.setCurrentHour(ultimaHora);
picker.setCurrentMinute(ultimoMinuto);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
ultimaHora = picker.getCurrentHour();
ultimoMinuto = picker.getCurrentMinute();
String tempo = String.valueOf(ultimaHora) + ":" + String.valueOf(ultimoMinuto);
if (callChangeListener(tempo)) {
persistString(tempo);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue,
Object defaultValue) {
String tempo = null;
if (restorePersistedValue) {
if (defaultValue == null) {
tempo = getPersistedString("00:00");
} else {
tempo = getPersistedString(defaultValue.toString());
}
} else {
tempo = defaultValue.toString();
}
ultimaHora = obterHora(tempo);
ultimoMinuto = obterMinuto(tempo);
}
}
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="listagem"
android:title="Modo de Listagem"
android:summary="Escolha o modo de listagem a ser utilizado"
android:entries="@array/nomes_ordenacao"
android:entryValues="@array/opcoes_ordenacao"
android:dialogTitle="Escolha o modo de listagem" />
<CheckBoxPreference
android:key="alarme"
android:title="Tocar Alarme no Almoço"
android:summary="Marque se deseja ser informado sobre a hora do almoço" />
<net.rafaeltoledo.restaurante.PreferenciaHorario
android:key="horario_alarme"
android:title="Horário do Alarme do Almoço"
android:defaultValue="12:00"
android:summary="Configure seu horário desejado para o alarme"
android:dependency="alarme" />
</PreferenceScreen>
package net.rafaeltoledo.restaurante;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ReceptorBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
<receiver android:name=".ReceptorBoot" android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
public static void configurarAlarme(Context contexto) {
AlarmManager gerenciador = (AlarmManager) contexto.getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(contexto);
String horario = preferencias.getString("horario_alarme", "12:00");
cal.set(Calendar.HOUR_OF_DAY, PreferenciaHorario.obterHora(horario));
cal.set(Calendar.MINUTE, PreferenciaHorario.obterMinuto(horario));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (cal.getTimeInMillis() < System.currentTimeMillis()) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}
gerenciador.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, obterIntentPendente(contexto));
}
public static void cancelarAlarme(Context contexto) {
AlarmManager gerenciador = (AlarmManager) contexto.getSystemService(Context.ALARM_SERVICE);
gerenciador.cancel(obterIntentPendente(contexto));
}
private static PendingIntent obterIntentPendente(Context contexto) {
Intent i = new Intent(contexto, ReceptorAlarme.class);
return PendingIntent.getBroadcast(contexto, 0, i, 0);
}
@Override
public void onReceive(Context context, Intent intent) {
configurarAlarme(context);
}
@Override
protected void onResume() {
super.onResume();
preferencias = PreferenceManager.getDefaultSharedPreferences(this);
preferencias.registerOnSharedPreferenceChangeListener(onChange);
}
@Override
protected void onPause() {
preferencias.unregisterOnSharedPreferenceChangeListener(onChange);
super.onPause();
}
OnSharedPreferenceChangeListener onChange = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if ("alarme".equals(key)) {
boolean habilitado = preferencias.getBoolean(key, false);
int flag = (habilitado ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
ComponentName componente = new ComponentName(EdicaoPreferencias.this, ReceptorBoot.class);
getPackageManager().setComponentEnabledSetting(componente, flag, PackageManager.DONT_KILL_APP);
if (habilitado) {
ReceptorBoot.configurarAlarme(EdicaoPreferencias.this);
} else {
ReceptorBoot.cancelarAlarme(EdicaoPreferencias.this);
}
} else if ("horario_alarme".equals(key)) {
ReceptorBoot.cancelarAlarme(EdicaoPreferencias.this);
ReceptorBoot.configurarAlarme(EdicaoPreferencias.this);
}
}
};
SharedPreferences preferencias = null;
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hora do almoço!"
android:textSize="30sp"
android:textStyle="bold" />
package net.rafaeltoledo.restaurante;
import android.app.Activity;
import android.os.Bundle;
public class AlarmeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarme);
}
}
package net.rafaeltoledo.restaurante;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ReceptorAlarme extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlarmeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
<receiver android:name=".ReceptorAlarme" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment