Notificaciones: WorkManager diario sustituye a AlarmManager+Service; canal, POST_NOTIFICATIONS runtime y control de duplicados
This commit is contained in:
1 parent
cab30c2a98
commit
f766e91ec2
12 files changed
+226
-181
No files matched your search
@@ -1,13 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<!-- For Admob -->
|
||||
<!-- Para AdMob -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<!-- Android 13+: sin esto no se ven las notificaciones -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:name=".CdfApplication"
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
@@ -23,15 +24,9 @@
|
||||
<activity android:name=".OptsActivity" android:label="Opciones" android:exported="false"/>
|
||||
<activity android:name=".FavsActivity" android:label="Favoritos" android:exported="false"/>
|
||||
<activity android:name=".AboutOfActivity" android:label="Acerca de" android:exported="false"/>
|
||||
<receiver
|
||||
android:name=".Alarm"
|
||||
android:process=":runalarm" />
|
||||
<service
|
||||
android:name=".NotificationHelper"
|
||||
android:process=":notif"/>
|
||||
<meta-data
|
||||
android:name="com.google.android.gms.ads.APPLICATION_ID"
|
||||
android:value="@string/admob_launch_api"/>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
</manifest>
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import java.util.Calendar;
|
||||
import android.os.PowerManager;
|
||||
import android.util.Log;
|
||||
|
||||
|
||||
/**
|
||||
* Created by http://stackoverflow.com/questions/4459058/alarm-manager-example
|
||||
* Modified by kprkpr
|
||||
*/
|
||||
|
||||
public class Alarm extends BroadcastReceiver
|
||||
{
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent)
|
||||
{
|
||||
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
|
||||
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
|
||||
wl.acquire(10);
|
||||
// Make notification appear
|
||||
context.startService(new Intent(context, NotificationHelper.class));
|
||||
|
||||
wl.release();
|
||||
}
|
||||
|
||||
public void putAlarm(Context context){
|
||||
Config conf = new Config(context);
|
||||
|
||||
/* Common vars for alarm config */
|
||||
Intent i = new Intent(context, Alarm.class);
|
||||
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
PendingIntent sender = PendingIntent.getBroadcast(context, 1, i, PendingIntent.FLAG_IMMUTABLE);
|
||||
|
||||
/* Cancel alarm first */
|
||||
alarmMgr.cancel(sender);
|
||||
|
||||
if (conf.getNotifOn() && !conf.getPersistNotifOn()){
|
||||
/* Here set the alarm to one time a day in selected date. Default: 8AM */
|
||||
Calendar time = Calendar.getInstance();
|
||||
/* Shedechule Alarm for tomorrow instead before now if alarm set to before. */
|
||||
if (Calendar.HOUR_OF_DAY > conf.getHour() || (Calendar.HOUR_OF_DAY == conf.getHour() && Calendar.MINUTE > conf.getMinute() )){
|
||||
/* Add a day */
|
||||
time.add(Calendar.DATE, 1);
|
||||
}
|
||||
time.set(Calendar.HOUR_OF_DAY, conf.getHour());
|
||||
time.set(Calendar.MINUTE, conf.getMinute());
|
||||
time.set(Calendar.SECOND, 0);
|
||||
Log.d("Next notification show",String.valueOf(time.getTime()));
|
||||
alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), 1000*3600*24, sender); // Repeat every day
|
||||
}
|
||||
|
||||
if (conf.getNotifOn() && conf.getPersistNotifOn()){
|
||||
/* Here set the alarm to one time a day in selected date. Default: 8AM */
|
||||
Calendar time = Calendar.getInstance();
|
||||
/* Set for 0:00:01 of next day */
|
||||
time.add(Calendar.DATE, 1);
|
||||
time.set(Calendar.HOUR_OF_DAY, 0);
|
||||
time.set(Calendar.MINUTE, 0);
|
||||
time.set(Calendar.SECOND, 1);
|
||||
Log.d("Next notification show",String.valueOf(time.getTime()));
|
||||
alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), 1000*3600*24, sender); // Repeat every day
|
||||
context.startService(new Intent(context, NotificationHelper.class)); /* Auto start service for show notif */
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
import android.app.Application;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
|
||||
/**
|
||||
* Arranque común de la app: crea el canal de notificación y asegura que el
|
||||
* trabajo diario esté programado (WorkManager lo persiste él solo; re-programar
|
||||
* en cada arranque corrige posibles desviaciones y cubre primera instalación).
|
||||
*/
|
||||
public class CdfApplication extends Application {
|
||||
|
||||
public static final String CHANNEL_ID = "notif";
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
NotificationChannel channel = new NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
getString(R.string.channel_name),
|
||||
NotificationManager.IMPORTANCE_DEFAULT);
|
||||
channel.setDescription(getString(R.string.channel_desc));
|
||||
NotificationManager nm = getSystemService(NotificationManager.class);
|
||||
nm.createNotificationChannel(channel);
|
||||
|
||||
NotifScheduler.schedule(this);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ public class Config {
|
||||
private final String KEY_NOTIFON = "Notify";
|
||||
private final String KEY_PERSISTNOTIFON = "PersistNotify";
|
||||
private final String KEY_FIRSTTIME = "FirstTime";
|
||||
private final String KEY_LASTNOTIFDAY = "LastNotifDay";
|
||||
|
||||
private Context emContext;
|
||||
|
||||
@@ -39,6 +40,7 @@ public class Config {
|
||||
}
|
||||
Boolean getPersistNotifOn(){return getSettings().getBoolean(KEY_PERSISTNOTIFON, false);}
|
||||
Boolean getFirstTime(){return getSettings().getBoolean(KEY_FIRSTTIME, true);}
|
||||
String getLastNotifDay(){return getSettings().getString(KEY_LASTNOTIFDAY, "");}
|
||||
|
||||
|
||||
void setHour(Integer hour){
|
||||
@@ -70,4 +72,10 @@ public class Config {
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
void setLastNotifDay(String day){
|
||||
SharedPreferences.Editor editor = getSettings().edit();
|
||||
editor.putString(KEY_LASTNOTIFDAY, day );
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.work.Worker;
|
||||
import androidx.work.WorkerParameters;
|
||||
|
||||
/**
|
||||
* Trabajo diario: muestra la notificación con la frase del día.
|
||||
* Lo programa NotifScheduler; WorkManager lo sobrevive a reinicios.
|
||||
*/
|
||||
public class DailyNotifWorker extends Worker {
|
||||
|
||||
public DailyNotifWorker(@NonNull Context context, @NonNull WorkerParameters params) {
|
||||
super(context, params);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Result doWork() {
|
||||
Config conf = new Config(getApplicationContext());
|
||||
if (conf.getNotifOn()) {
|
||||
Notif.show(getApplicationContext(), conf);
|
||||
}
|
||||
return Result.success();
|
||||
}
|
||||
}
|
||||
@@ -112,10 +112,6 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
|
||||
|
||||
|
||||
/* Configure alarm */
|
||||
Alarm alarm = new Alarm();
|
||||
alarm.putAlarm(this);
|
||||
|
||||
/* Register context menu */
|
||||
registerForContextMenu(txtfraseText);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import androidx.core.app.NotificationCompat;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Construcción y muestra de la notificación de la frase del día.
|
||||
* La usa el DailyNotifWorker y también OptsActivity para mostrarla al activar
|
||||
* el modo persistente.
|
||||
*/
|
||||
public final class Notif {
|
||||
|
||||
private static final int NOTIF_ID = 1;
|
||||
|
||||
private Notif() {
|
||||
}
|
||||
|
||||
/** Muestra (o refresca) la notificación de hoy, respetando el no-duplicar diario. */
|
||||
public static void show(Context context, Config conf) {
|
||||
String today = todayKey();
|
||||
if (!conf.getPersistNotifOn() && today.equals(conf.getLastNotifDay())) {
|
||||
return; // ya notificada hoy (modo no persistente)
|
||||
}
|
||||
DatabaseHelper db = new DatabaseHelper(context);
|
||||
String frase = db.getFraseFromID(db.getIDFraseHoy());
|
||||
|
||||
Intent openIntent = new Intent(context, MainActivity.class);
|
||||
PendingIntent notifIntent = PendingIntent.getActivity(
|
||||
context, 0, openIntent, PendingIntent.FLAG_IMMUTABLE);
|
||||
|
||||
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CdfApplication.CHANNEL_ID)
|
||||
.setContentIntent(notifIntent)
|
||||
.setContentTitle(context.getString(R.string.notif_title))
|
||||
.setStyle(new NotificationCompat.BigTextStyle().bigText(frase))
|
||||
.setContentText(frase)
|
||||
.setSmallIcon(R.drawable.notifwhite)
|
||||
.setLargeIcon(android.graphics.BitmapFactory.decodeResource(
|
||||
context.getResources(), R.mipmap.ic_launcher));
|
||||
|
||||
if (conf.getPersistNotifOn()) {
|
||||
builder.setOngoing(true);
|
||||
}
|
||||
|
||||
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
nm.notify(NOTIF_ID, builder.build());
|
||||
conf.setLastNotifDay(today);
|
||||
}
|
||||
|
||||
/** Cancela la notificación visible (p.ej. al cambiar opciones). */
|
||||
public static void cancel(Context context) {
|
||||
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
|
||||
nm.cancel(NOTIF_ID);
|
||||
}
|
||||
|
||||
/** Fecha de hoy como yyyyMMdd, para el control de "ya notificada hoy". */
|
||||
public static String todayKey() {
|
||||
return new SimpleDateFormat("yyyyMMdd", Locale.US).format(Calendar.getInstance().getTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.work.ExistingPeriodicWorkPolicy;
|
||||
import androidx.work.PeriodicWorkRequest;
|
||||
import androidx.work.WorkManager;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* Programa el trabajo diario de la notificación.
|
||||
* - Modo normal: a la hora elegida por el usuario (por defecto 8:00).
|
||||
* - Modo persistente: a las 00:01 (la frase cambia al cambiar de día).
|
||||
* WorkManager persiste el trabajo ante reinicios y Doze (ventana flexible).
|
||||
*/
|
||||
public final class NotifScheduler {
|
||||
|
||||
public static final String WORK_NAME = "dailyNotif";
|
||||
|
||||
private NotifScheduler() {
|
||||
}
|
||||
|
||||
/** Reprograma el trabajo diario según la configuración actual. */
|
||||
public static void schedule(Context context) {
|
||||
Config conf = new Config(context);
|
||||
WorkManager wm = WorkManager.getInstance(context);
|
||||
|
||||
if (!conf.getNotifOn()) {
|
||||
wm.cancelUniqueWork(WORK_NAME);
|
||||
return;
|
||||
}
|
||||
|
||||
Calendar trigger = Calendar.getInstance();
|
||||
if (conf.getPersistNotifOn()) {
|
||||
trigger.add(Calendar.DATE, 1);
|
||||
trigger.set(Calendar.HOUR_OF_DAY, 0);
|
||||
trigger.set(Calendar.MINUTE, 1);
|
||||
trigger.set(Calendar.SECOND, 0);
|
||||
} else {
|
||||
trigger.set(Calendar.HOUR_OF_DAY, conf.getHour());
|
||||
trigger.set(Calendar.MINUTE, conf.getMinute());
|
||||
trigger.set(Calendar.SECOND, 0);
|
||||
if (!trigger.after(Calendar.getInstance())) {
|
||||
trigger.add(Calendar.DATE, 1);
|
||||
}
|
||||
}
|
||||
|
||||
long delayMillis = trigger.getTimeInMillis() - System.currentTimeMillis();
|
||||
|
||||
PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(
|
||||
DailyNotifWorker.class, 24, TimeUnit.HOURS)
|
||||
.setInitialDelay(delayMillis, TimeUnit.MILLISECONDS)
|
||||
.build();
|
||||
|
||||
wm.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.REPLACE, request);
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.os.IBinder;
|
||||
import androidx.core.app.NotificationCompat;
|
||||
import android.util.Log;
|
||||
|
||||
|
||||
/**
|
||||
* Created by kprkpr on 20/03/17.
|
||||
*/
|
||||
|
||||
public class NotificationHelper extends Service {
|
||||
private static final String TAG = "NotificationHelper";
|
||||
DatabaseHelper db = new DatabaseHelper(this);
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent i) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(final Intent intent, int flags, int startId) {
|
||||
|
||||
new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Log.d(TAG, "Service Started");
|
||||
// El servicio se finaliza a sí mismo cuando finaliza su
|
||||
// trabajo.
|
||||
final Config conf = new Config(NotificationHelper.this);
|
||||
try {
|
||||
// Instanciamos e inicializamos nuestro manager.
|
||||
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
|
||||
nm.cancel(1); /* Cancel first */
|
||||
if (conf.getNotifOn().equals(true)) { /* Only set things if notification is enabled */
|
||||
Intent OpenIntent = new Intent(NotificationHelper.this, MainActivity.class);
|
||||
PendingIntent notifIntent = PendingIntent.getActivity(NotificationHelper.this, 0, OpenIntent, PendingIntent.FLAG_IMMUTABLE);
|
||||
|
||||
CharSequence ticker = "Frase del día";
|
||||
CharSequence contentTitle = "Frase de hoy:";
|
||||
CharSequence contentText = db.getFraseFromID(db.getIDFraseHoy());
|
||||
NotificationCompat.Builder notibuilder = new NotificationCompat.Builder(NotificationHelper.this,"notif")
|
||||
.setContentIntent(notifIntent)
|
||||
.setTicker(ticker)
|
||||
.setContentTitle(contentTitle)
|
||||
.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText)) /* For big texts */
|
||||
.setContentText(contentText) /* For when bigText cant be show */
|
||||
.setLargeIcon(BitmapFactory.decodeResource(NotificationHelper.this.getResources(), R.mipmap.ic_launcher));
|
||||
/* If lollipop, new white icon, if not, grey icon */
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
|
||||
notibuilder.setSmallIcon(R.drawable.notifwhite);
|
||||
} else{
|
||||
notibuilder.setSmallIcon(R.drawable.notifgris);
|
||||
}
|
||||
|
||||
Notification noti = notibuilder.build();
|
||||
if (conf.getPersistNotifOn().equals(true)) {
|
||||
noti.flags = Notification.FLAG_ONGOING_EVENT;
|
||||
}
|
||||
nm.notify(1, noti);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}).start();
|
||||
Log.d(TAG, "Service Finished");
|
||||
this.stopSelf();
|
||||
return super.onStartCommand(intent, flags, startId);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
import android.app.NotificationManager;
|
||||
import android.content.Intent;
|
||||
import android.Manifest;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import android.view.View;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Button;
|
||||
@@ -99,19 +102,31 @@ public class OptsActivity extends AppCompatActivity {
|
||||
conf.setNotifOn(chkalarm.isChecked());
|
||||
conf.setPersistNotifOn(chkpersistent.isChecked());
|
||||
|
||||
/* Cancel notif when save changes first */
|
||||
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
|
||||
nm.cancel(1);
|
||||
if (chkalarm.isChecked() && !notificationsEnabled()) {
|
||||
/* Android 13+: pedir permiso para poder mostrar la notificación */
|
||||
ActivityCompat.requestPermissions(OptsActivity.this,
|
||||
new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1);
|
||||
}
|
||||
|
||||
Alarm alarm = new Alarm();
|
||||
alarm.putAlarm(OptsActivity.this);
|
||||
/* Cancel notif when save changes first */
|
||||
Notif.cancel(OptsActivity.this);
|
||||
|
||||
NotifScheduler.schedule(OptsActivity.this);
|
||||
if (chkpersistent.isChecked() && chkalarm.isChecked()) {
|
||||
OptsActivity.this.startService(new Intent(OptsActivity.this, NotificationHelper.class));
|
||||
Notif.show(OptsActivity.this, conf); /* Auto show notif for persistent mode */
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
private boolean notificationsEnabled() {
|
||||
if (Build.VERSION.SDK_INT < 33) {
|
||||
return true;
|
||||
}
|
||||
return ContextCompat.checkSelfPermission(OptsActivity.this,
|
||||
Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
public void setEnabledParts(){
|
||||
/* I have to set vars again because is out of onCreate */
|
||||
Spinner notifHour = findViewById(R.id.spinnerHour);
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
<string name="favorites">Favoritos</string>
|
||||
<string name="options">Opciones</string>
|
||||
<string name="aboutOf">Acerca de</string>
|
||||
<string name="sharefrom"> -A través de Calendario de Frases, consíguela aquí https://goo.gl/m4qzKI -</string>
|
||||
<string name="sharefrom"> -A través de Calendario de Frases, consíguela aquí https://play.google.com/store/apps/details?id=com.jkanetwork.st.calendariodefrases -</string>
|
||||
<string name="channel_name">Frase del día</string>
|
||||
<string name="channel_desc">Notificación diaria con la frase del día</string>
|
||||
<string name="notif_title">Frase de hoy:</string>
|
||||
|
||||
</resources>
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
#Tue Oct 20 12:44:21 UTC 2026
|
||||
VERSION_CODE=361
|
||||
#Tue Oct 20 12:47:34 UTC 2026
|
||||
VERSION_CODE=364
|
||||
Reference in new issue
Block a user