Compare commits
5
Commits
592e96366d
...
4a4ed7162d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a4ed7162d | ||
|
|
a003a94e7a | ||
|
|
6f7bfaff9c | ||
|
|
f766e91ec2 | ||
|
|
cab30c2a98 |
No files matched your search
@@ -1,6 +1,7 @@
|
|||||||
*.iml
|
*.iml
|
||||||
.gradle
|
.gradle
|
||||||
/local.properties
|
/local.properties
|
||||||
|
/keystore.properties
|
||||||
/.idea/workspace.xml
|
/.idea/workspace.xml
|
||||||
/.idea/libraries
|
/.idea/libraries
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# AGENTS.md — Calendario de Frases
|
||||||
|
|
||||||
|
App Android en **Java** (sin Kotlin, sin Compose, sin DI): Activities + XML
|
||||||
|
layouts + SQLite. Mantener el estilo simple del proyecto; no introducir
|
||||||
|
frameworks salvo que Kevin lo pida.
|
||||||
|
|
||||||
|
## Comandos
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./gradlew assembleDebug # compilar (sube versionCode solo)
|
||||||
|
./gradlew assembleRelease # release con R8 minify
|
||||||
|
./gradlew test # tests unitarios
|
||||||
|
./gradlew lint # lint Android
|
||||||
|
python3 tools/build_master_db.py # regenerar assets/frases.db desde res/raw
|
||||||
|
```
|
||||||
|
|
||||||
|
SDK: `~/android-sdk` (compileSdk 37, build-tools 36). JDK 17+.
|
||||||
|
|
||||||
|
## Reglas del proyecto
|
||||||
|
|
||||||
|
1. **Secretos**: `app/src/main/res/values/admob.xml` (IDs AdMob) y
|
||||||
|
`keystore.properties` están en .gitignore. NO commitear. La plantilla es
|
||||||
|
`admob.example.xml` (raíz). Sin admob.xml no compila: documentado en README.
|
||||||
|
2. **BD maestra vs BD usuario**:
|
||||||
|
- Maestra (`assets/frases.db`): frases + autores, read-only en runtime.
|
||||||
|
Cambios de contenido SOLO vía `res/raw/sqlfrases`/`sqlautores` +
|
||||||
|
regenerar con `tools/build_master_db.py` subiendo `MASTER_DB_VERSION`.
|
||||||
|
JAMÁS escribir en ella desde la app.
|
||||||
|
- Usuario (`user.db`): `frasesG` (día→frase) y `frasesFav`. Solo la app la
|
||||||
|
toca. Los IDs del maestro son estables: los favoritos del usuario
|
||||||
|
referencian `_id` del maestro.
|
||||||
|
- Migración legacy: `DatabaseHelper.migrateLegacyIfNeeded()` vuelca la vieja
|
||||||
|
`database.db` a `user.db` y la renombra a `.bak`. One-shot.
|
||||||
|
3. **versionCode**: `app/version.count` se auto-incrementa en CADA compilación.
|
||||||
|
No commitear subidas accidentales del counter... en la práctica se commitea
|
||||||
|
tal cual (histórico del repo). El versionName se sube a mano en
|
||||||
|
`app/build.gradle` al publicar.
|
||||||
|
4. **Notificaciones**: WorkManager (`NotifScheduler.schedule()` reprograma;
|
||||||
|
`DailyNotifWorker` ejecuta). No volver a AlarmManager/Service (crasheaba en
|
||||||
|
Android 8+). Permiso POST_NOTIFICATIONS se pide en OptsActivity.
|
||||||
|
5. **AdMob**: siempre UMP consent antes de `MobileAds.initialize` (política
|
||||||
|
Google en EEA). `initialize` SIEMPRE en hilo background.
|
||||||
|
6. **Estilo código**: sin switch sobre R.id (AGP 9 genera R no-final; usar
|
||||||
|
if-else). Strings de UI SIEMPRE en `res/values/strings.xml`. Queries SQLite
|
||||||
|
SIEMPRE parametrizadas (`?` + selectionArgs), jamás concatenación.
|
||||||
|
7. **robotocalendarview** (jitpack, 2017): lib pre-AndroidX; por eso
|
||||||
|
`android.enableJetifier=true` sigue activo. No actualizar la lib a ciegas.
|
||||||
|
8. **Idioma**: código y comentarios en inglés (histórico del repo), UI en
|
||||||
|
español en strings.xml, docs (README/este fichero) en español.
|
||||||
|
|
||||||
|
## Verificación antes de dar por cerrado un cambio
|
||||||
|
|
||||||
|
- `./gradlew assembleDebug assembleRelease` verde
|
||||||
|
- Instalar en emulador (`adb install -r`) y arrancar sin FATAL en logcat
|
||||||
|
- Si se tocó BD: verificar migración con una database.db legacy de prueba
|
||||||
@@ -1,16 +1,73 @@
|
|||||||
# Codigo fuente de "Calendario De Frases"
|
# Calendario De Frases
|
||||||
|
|
||||||
Calendario de frases es una aplicacion para Android en la que todos los días tendrás una nueva frase o refrán en tu lugar de notificaciones
|
Aplicación Android (Java) que muestra cada día una frase o refrán en el lugar de
|
||||||
|
notificaciones. Con el calendario integrado puedes ver frases anteriores, marcar
|
||||||
|
favoritos y compartirlos.
|
||||||
|
|
||||||
Con un calendario integrado, podrás ver frases anteriores, marcar como favoritos, o compartirlas con tus amigos
|
Descárgala en Google Play: https://play.google.com/store/apps/details?id=com.jkanetwork.st.calendariodefrases
|
||||||
|
|
||||||
Descargalo en Google Play: https://play.google.com/store/apps/details?id=com.jkanetwork.st.calendariodefrases
|
## Requisitos
|
||||||
|
|
||||||
## Problemas al compilar la aplicación
|
- Android Studio (o JDK 17+ con el SDK de Android: compileSdk 37, build-tools 36)
|
||||||
|
- Para compilar release firmado: `keystore.properties` en la raíz (ver más abajo)
|
||||||
|
|
||||||
La aplicación puede dar problemas de compilación al faltar los 2 strings de la API de Admob (No subidas porque son propias, evitamos un mal uso de la API).
|
## Compilar
|
||||||
Para solucionarlo solo hay que quitar la parte de admob
|
|
||||||
|
```bash
|
||||||
|
./gradlew assembleDebug # APK debug
|
||||||
|
./gradlew assembleRelease # APK release (minify + shrink + firma si hay keystore)
|
||||||
|
```
|
||||||
|
|
||||||
|
El `versionCode` se auto-incrementa en cada compilación (`app/version.count`).
|
||||||
|
|
||||||
|
### IDs de AdMob (obligatorio)
|
||||||
|
|
||||||
|
La app integra AdMob (banner) con consentimiento UMP. Los IDs de AdMob viven en
|
||||||
|
`app/src/main/res/values/admob.xml`, que está **ignorado por git** para no exponerlos.
|
||||||
|
|
||||||
|
Antes de compilar por primera vez:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp admob.example.xml app/src/main/res/values/admob.xml
|
||||||
|
```
|
||||||
|
|
||||||
|
El example trae los IDs de **test** públicos de Google, válidos para desarrollo.
|
||||||
|
Para producción, pon ahí tus IDs reales de AdMob (app ID y banner).
|
||||||
|
|
||||||
|
### Firma de release
|
||||||
|
|
||||||
|
`keystore.properties` (raíz, ignorado por git):
|
||||||
|
|
||||||
|
```properties
|
||||||
|
storeFile=mi.keystore
|
||||||
|
storePassword=***
|
||||||
|
keyAlias=***
|
||||||
|
keyPassword=***
|
||||||
|
```
|
||||||
|
|
||||||
|
Si no existe, el release se compila sin firmar.
|
||||||
|
|
||||||
|
## Bases de datos
|
||||||
|
|
||||||
|
- `app/src/main/assets/frases.db`: BD **maestra** (frases + autores), read-only,
|
||||||
|
generada con `python3 tools/build_master_db.py` desde `res/raw/sqlfrases` y
|
||||||
|
`res/raw/sqlautores`. Al publicar contenido nuevo: edita los raw, sube
|
||||||
|
`MASTER_DB_VERSION` en el script, regenera y compila. La app recopia el
|
||||||
|
maestro cuando detecta un `user_version` mayor; los datos del usuario nunca
|
||||||
|
se tocan.
|
||||||
|
- `user.db` (en el dispositivo): frases asignadas por día (`frasesG`) y
|
||||||
|
favoritos (`frasesFav`). Es la BD del usuario y sobrevive a todas las
|
||||||
|
actualizaciones del maestro.
|
||||||
|
- Los usuarios de versiones anteriores se migran automáticamente desde la vieja
|
||||||
|
`database.db` (queda como `.bak`).
|
||||||
|
|
||||||
|
## Notificaciones
|
||||||
|
|
||||||
|
WorkManager programa la notificación diaria (sobrevive reinicios y Doze). En
|
||||||
|
Android 13+ se pide el permiso `POST_NOTIFICATIONS` al activar la notificación
|
||||||
|
en Opciones. Modo persistente: notificación continua que se refresca a las
|
||||||
|
00:01.
|
||||||
|
|
||||||
## Licencia
|
## Licencia
|
||||||
|
|
||||||
Mire el fichero LICENSE.md para detalles, usamos licencia GPL
|
GPL, mira LICENSE.md para detalles.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<!-- Copia este fichero como admob.xml (gitignored) con tus IDs reales de AdMob.
|
||||||
|
La app no compila sin él: AndroidManifest y activity_main lo referencian. -->
|
||||||
|
<!-- IDs de TEST públicos de Google: no producen ingresos ni violan política -->
|
||||||
|
<string name="admob_launch_api">ca-app-pub-3940256099942544~3347511713</string>
|
||||||
|
<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
|
||||||
|
</resources>
|
||||||
+47
-21
@@ -1,45 +1,71 @@
|
|||||||
apply plugin: 'com.android.application'
|
plugins {
|
||||||
|
id 'com.android.application'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Credenciales de firma de release: viven en keystore.properties (ignorado por git).
|
||||||
|
// Si el fichero no existe el build sigue funcionando (release sin firmar).
|
||||||
|
def keystorePropsFile = rootProject.file('keystore.properties')
|
||||||
|
def keystoreProps = new Properties()
|
||||||
|
if (keystorePropsFile.exists()) {
|
||||||
|
keystoreProps.load(new FileInputStream(keystorePropsFile))
|
||||||
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
|
namespace 'com.jkanetwork.st.calendariodefrases'
|
||||||
|
compileSdk 37
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId "com.jkanetwork.st.calendariodefrases"
|
applicationId "com.jkanetwork.st.calendariodefrases"
|
||||||
minSdkVersion 21
|
minSdk 26
|
||||||
compileSdk 34
|
targetSdk 36
|
||||||
targetSdkVersion 34
|
versionName "1.4.0"
|
||||||
versionName "1.3.5"
|
// Sube automáticamente la build en cada compilación
|
||||||
// Sube automáticamente la build en cada
|
|
||||||
def versionPropsFile = file('version.count')
|
def versionPropsFile = file('version.count')
|
||||||
def Properties versionProps = new Properties()
|
def Properties versionProps = new Properties()
|
||||||
|
|
||||||
versionProps.load(new FileInputStream(versionPropsFile))
|
versionProps.load(new FileInputStream(versionPropsFile))
|
||||||
|
|
||||||
def code = versionProps['VERSION_CODE'].toInteger() + 1
|
def code = versionProps['VERSION_CODE'].toInteger() + 1
|
||||||
versionCode code
|
|
||||||
versionProps['VERSION_CODE'] = code.toString()
|
versionProps['VERSION_CODE'] = code.toString()
|
||||||
versionProps.store(versionPropsFile.newWriter(), null)
|
versionProps.store(versionPropsFile.newWriter(), null)
|
||||||
|
versionCode code
|
||||||
|
// Fin de subida automática de build
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
signingConfigs {
|
||||||
|
release {
|
||||||
|
if (keystorePropsFile.exists()) {
|
||||||
|
storeFile file(keystoreProps['storeFile'])
|
||||||
|
storePassword keystoreProps['storePassword']
|
||||||
|
keyAlias keystoreProps['keyAlias']
|
||||||
|
keyPassword keystoreProps['keyPassword']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
minifyEnabled true
|
minifyEnabled true
|
||||||
shrinkResources true
|
shrinkResources true
|
||||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||||
|
if (keystorePropsFile.exists()) {
|
||||||
|
signingConfig signingConfigs.release
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
namespace 'com.jkanetwork.st.calendariodefrases'
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility JavaVersion.VERSION_17
|
||||||
|
targetCompatibility JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
implementation 'androidx.appcompat:appcompat:1.8.0'
|
||||||
/*androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
|
implementation 'androidx.core:core:1.19.1'
|
||||||
exclude group: 'com.android.support', module: 'support-annotations'
|
implementation 'androidx.work:work-runtime:2.12.0'
|
||||||
})*/
|
|
||||||
implementation 'androidx.appcompat:appcompat:1.6.1'
|
|
||||||
implementation 'androidx.core:core:1.12.0'
|
|
||||||
implementation 'com.google.android.material:material:1.11.0'
|
|
||||||
implementation 'com.github.marcohc:robotocalendarview:3.1.1'
|
implementation 'com.github.marcohc:robotocalendarview:3.1.1'
|
||||||
implementation 'com.google.android.gms:play-services-ads:23.0.0'
|
implementation 'com.google.android.gms:play-services-ads:25.5.0'
|
||||||
//compile 'com.tappx.sdk.android:tappx-sdk:3.+'
|
implementation 'com.google.android.ump:user-messaging-platform:4.0.0'
|
||||||
//testImplementation 'junit:junit:4.12'
|
testImplementation 'junit:junit:4.13.2'
|
||||||
}
|
}
|
||||||
Vendored
+7
-37
@@ -1,39 +1,9 @@
|
|||||||
# Add project specific ProGuard rules here.
|
# Reglas de keep para anuncios y UMP ya vienen empaquetadas en las propias libs.
|
||||||
# By default, the flags in this file are appended to flags specified
|
# Aquí solo reglas específicas del proyecto.
|
||||||
# in /mnt/kevinmem/Android/sdkLinux/tools/proguard/proguard-android.txt
|
|
||||||
# You can edit the include path and order by changing the proguardFiles
|
|
||||||
# directive in build.gradle.
|
|
||||||
#
|
|
||||||
# For more details, see
|
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
|
||||||
|
|
||||||
# Add any project specific keep options here:
|
# robotocalendarview (jitpack, sin reglas empaquetadas): conservar la vista y su listener
|
||||||
|
-keep class com.marcohc.robotocalendar.** { *; }
|
||||||
|
|
||||||
# If your project uses WebView with JS, uncomment the following
|
# Crash legibles si hace falta debug
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
-keepattributes SourceFile,LineNumberTable
|
||||||
# class:
|
-renamesourcefileattribute SourceFile
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
|
||||||
# public *;
|
|
||||||
#}
|
|
||||||
|
|
||||||
# Uncomment this to preserve the line number information for
|
|
||||||
# debugging stack traces.
|
|
||||||
#-keepattributes SourceFile,LineNumberTable
|
|
||||||
|
|
||||||
# If you keep the line number information, uncomment this to
|
|
||||||
# hide the original source file name.
|
|
||||||
#-renamesourcefileattribute SourceFile
|
|
||||||
|
|
||||||
-keepattributes *Annotation*
|
|
||||||
-keepclassmembers class com.google.**.R$* {
|
|
||||||
public static <fields>;
|
|
||||||
}
|
|
||||||
-keep public class com.google.ads.** {*;}
|
|
||||||
-keep public class com.google.android.gms.** {*;}
|
|
||||||
-keep public class com.tappx.** { *; }
|
|
||||||
|
|
||||||
-ignorewarnings
|
|
||||||
|
|
||||||
-keep class * {
|
|
||||||
public private *;
|
|
||||||
}
|
|
||||||
-26
@@ -1,26 +0,0 @@
|
|||||||
package com.jkanetwork.st.calendariodefrases;
|
|
||||||
|
|
||||||
import android.content.Context;
|
|
||||||
import android.support.test.InstrumentationRegistry;
|
|
||||||
import android.support.test.runner.AndroidJUnit4;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Instrumentation test, which will execute on an Android device.
|
|
||||||
*
|
|
||||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
|
||||||
*/
|
|
||||||
@RunWith(AndroidJUnit4.class)
|
|
||||||
public class ExampleInstrumentedTest {
|
|
||||||
@Test
|
|
||||||
public void useAppContext() throws Exception {
|
|
||||||
// Context of the app under test.
|
|
||||||
Context appContext = InstrumentationRegistry.getTargetContext();
|
|
||||||
|
|
||||||
assertEquals("com.jkanetwork.st.unafrasealdia", appContext.getPackageName());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
<!-- Para AdMob -->
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
|
||||||
<!-- For Admob -->
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<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
|
<application
|
||||||
|
android:name=".CdfApplication"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
@@ -23,15 +24,9 @@
|
|||||||
<activity android:name=".OptsActivity" android:label="Opciones" android:exported="false"/>
|
<activity android:name=".OptsActivity" android:label="Opciones" android:exported="false"/>
|
||||||
<activity android:name=".FavsActivity" android:label="Favoritos" android:exported="false"/>
|
<activity android:name=".FavsActivity" android:label="Favoritos" android:exported="false"/>
|
||||||
<activity android:name=".AboutOfActivity" android:label="Acerca de" 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
|
<meta-data
|
||||||
android:name="com.google.android.gms.ads.APPLICATION_ID"
|
android:name="com.google.android.gms.ads.APPLICATION_ID"
|
||||||
android:value="@string/admob_launch_api"/>
|
android:value="@string/admob_launch_api"/>
|
||||||
</application>
|
</application>
|
||||||
|
|
||||||
</manifest>
|
</manifest>
|
||||||
Binary file not shown.
@@ -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_NOTIFON = "Notify";
|
||||||
private final String KEY_PERSISTNOTIFON = "PersistNotify";
|
private final String KEY_PERSISTNOTIFON = "PersistNotify";
|
||||||
private final String KEY_FIRSTTIME = "FirstTime";
|
private final String KEY_FIRSTTIME = "FirstTime";
|
||||||
|
private final String KEY_LASTNOTIFDAY = "LastNotifDay";
|
||||||
|
|
||||||
private Context emContext;
|
private Context emContext;
|
||||||
|
|
||||||
@@ -39,6 +40,7 @@ public class Config {
|
|||||||
}
|
}
|
||||||
Boolean getPersistNotifOn(){return getSettings().getBoolean(KEY_PERSISTNOTIFON, false);}
|
Boolean getPersistNotifOn(){return getSettings().getBoolean(KEY_PERSISTNOTIFON, false);}
|
||||||
Boolean getFirstTime(){return getSettings().getBoolean(KEY_FIRSTTIME, true);}
|
Boolean getFirstTime(){return getSettings().getBoolean(KEY_FIRSTTIME, true);}
|
||||||
|
String getLastNotifDay(){return getSettings().getString(KEY_LASTNOTIFDAY, "");}
|
||||||
|
|
||||||
|
|
||||||
void setHour(Integer hour){
|
void setHour(Integer hour){
|
||||||
@@ -70,4 +72,10 @@ public class Config {
|
|||||||
editor.apply();
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,275 +1,342 @@
|
|||||||
package com.jkanetwork.st.calendariodefrases;
|
package com.jkanetwork.st.calendariodefrases;
|
||||||
|
|
||||||
|
import android.content.ContentValues;
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.database.Cursor;
|
import android.database.Cursor;
|
||||||
import android.database.sqlite.SQLiteDatabase;
|
import android.database.sqlite.SQLiteDatabase;
|
||||||
import android.database.sqlite.SQLiteOpenHelper;
|
import android.database.sqlite.SQLiteOpenHelper;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.File;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Calendar;
|
import java.util.Date;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Locale;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
public class DatabaseHelper extends SQLiteOpenHelper {
|
/**
|
||||||
private static final int DATABASE_VERSION = 12;
|
* Gestor de las dos bases de datos:
|
||||||
private static final String DATABASE_NAME = "database.db";
|
*
|
||||||
private final Context contextdb;
|
* - frases.db (assets): BD maestra de frases y autores. Read-only, se
|
||||||
|
* recopia desde el asset cuando su user_version sube (nueva versión de
|
||||||
|
* la app con contenido nuevo). El contenido no se modifica en runtime.
|
||||||
|
*
|
||||||
|
* - user.db: datos del usuario (día->frase asignada y favoritos). Se crea
|
||||||
|
* vacía y solo la app la toca. Las actualizaciones del maestro JAMÁS
|
||||||
|
* la afectan.
|
||||||
|
*
|
||||||
|
* Migración one-shot: si existe la antigua database.db (todo mezclado),
|
||||||
|
* se vuelcan frasesFav y frasesG a user.db y la vieja queda como .bak.
|
||||||
|
*
|
||||||
|
* El maestro se regenera con tools/build_master_db.py desde res/raw
|
||||||
|
* (fuente editable); al cambiar el contenido se sube MASTER_DB_VERSION
|
||||||
|
* en el script.
|
||||||
|
*/
|
||||||
|
public class DatabaseHelper {
|
||||||
|
|
||||||
|
private static final String TAG = "DatabaseHelper";
|
||||||
|
private static final String LEGACY_DB_NAME = "database.db";
|
||||||
|
private static final String USER_DB_NAME = "user.db";
|
||||||
|
private static final int USER_DB_VERSION = 1;
|
||||||
|
|
||||||
|
private final Context context;
|
||||||
|
private final SQLiteDatabase masterDb;
|
||||||
|
private final SQLiteDatabase userDb;
|
||||||
|
|
||||||
|
/* Versión del asset leída una vez por proceso (el asset no cambia en caliente) */
|
||||||
|
private static Integer cachedAssetVersion;
|
||||||
|
|
||||||
public DatabaseHelper(Context context) {
|
public DatabaseHelper(Context context) {
|
||||||
super(context, DATABASE_NAME, null, DATABASE_VERSION);
|
this.context = context.getApplicationContext();
|
||||||
contextdb = context;
|
this.masterDb = openMaster();
|
||||||
|
this.userDb = new UserDbOpenHelper(this.context).getWritableDatabase();
|
||||||
|
migrateLegacyIfNeeded();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* BD maestra (read-only, copia del asset) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
private SQLiteDatabase openMaster() {
|
||||||
|
File dbFile = context.getDatabasePath("frases_master.db");
|
||||||
|
if (!dbFile.exists() || getFileVersion(dbFile) < assetVersion()) {
|
||||||
|
copyAsset("frases.db", dbFile);
|
||||||
|
}
|
||||||
|
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int assetVersion() {
|
||||||
|
if (cachedAssetVersion != null) {
|
||||||
|
return cachedAssetVersion;
|
||||||
|
}
|
||||||
|
File tmp = new File(context.getCacheDir(), "frases_asset_probe.db");
|
||||||
|
try {
|
||||||
|
copyAsset("frases.db", tmp);
|
||||||
|
cachedAssetVersion = getFileVersion(tmp);
|
||||||
|
} finally {
|
||||||
|
tmp.delete();
|
||||||
|
}
|
||||||
|
return cachedAssetVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int getFileVersion(File dbFile) {
|
||||||
|
SQLiteDatabase db = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||||
|
try {
|
||||||
|
return db.getVersion();
|
||||||
|
} finally {
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void copyAsset(String assetName, File dest) {
|
||||||
|
try {
|
||||||
|
dest.getParentFile().mkdirs();
|
||||||
|
try (InputStream in = context.getAssets().open(assetName);
|
||||||
|
OutputStream out = new FileOutputStream(dest)) {
|
||||||
|
byte[] buf = new byte[8192];
|
||||||
|
int n;
|
||||||
|
while ((n = in.read(buf)) > 0) {
|
||||||
|
out.write(buf, 0, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
Log.e(TAG, "copyAsset " + assetName + ": " + e);
|
||||||
|
throw new RuntimeException("No se pudo copiar " + assetName, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* BD de usuario */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
private static class UserDbOpenHelper extends SQLiteOpenHelper {
|
||||||
|
UserDbOpenHelper(Context context) {
|
||||||
|
super(context, USER_DB_NAME, null, USER_DB_VERSION);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onCreate(SQLiteDatabase db) {
|
||||||
|
db.execSQL("CREATE TABLE frasesG (" +
|
||||||
|
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
||||||
|
"`Tday` TEXT NOT NULL UNIQUE," +
|
||||||
|
"`IDFrase` INTEGER NOT NULL" +
|
||||||
|
")");
|
||||||
|
db.execSQL("CREATE TABLE frasesFav (" +
|
||||||
|
"`IDFrase` INTEGER NOT NULL UNIQUE" +
|
||||||
|
")");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
|
||||||
|
// v1: sin cambios aún
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Migración desde la BD mezclada antigua (one-shot) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
private void migrateLegacyIfNeeded() {
|
||||||
|
File legacy = context.getDatabasePath(LEGACY_DB_NAME);
|
||||||
|
if (!legacy.exists()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
SQLiteDatabase old = SQLiteDatabase.openDatabase(legacy.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||||
|
try {
|
||||||
|
try (Cursor c = old.rawQuery("SELECT IDFrase FROM frasesFav", null)) {
|
||||||
|
while (c.moveToNext()) {
|
||||||
|
ContentValues cv = new ContentValues();
|
||||||
|
cv.put("IDFrase", c.getInt(0));
|
||||||
|
userDb.insertWithOnConflict("frasesFav", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (Cursor c = old.rawQuery("SELECT Tday, IDFrase FROM frasesG", null)) {
|
||||||
|
while (c.moveToNext()) {
|
||||||
|
ContentValues cv = new ContentValues();
|
||||||
|
cv.put("Tday", c.getString(0));
|
||||||
|
cv.put("IDFrase", c.getInt(1));
|
||||||
|
userDb.insertWithOnConflict("frasesG", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
old.close();
|
||||||
|
}
|
||||||
|
/* La vieja se conserva como .bak; si ya había un bak, gana la nueva */
|
||||||
|
File bak = new File(legacy.getPath() + ".bak");
|
||||||
|
if (bak.exists()) {
|
||||||
|
bak.delete();
|
||||||
|
}
|
||||||
|
if (!legacy.renameTo(bak)) {
|
||||||
|
legacy.delete();
|
||||||
|
}
|
||||||
|
Log.i(TAG, "Migrada " + LEGACY_DB_NAME + " -> " + USER_DB_NAME);
|
||||||
|
} catch (Exception e) {
|
||||||
|
Log.e(TAG, "migrateLegacy: " + e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Queries públicas */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
/** Return the sentence passing the ID of it */
|
/** Return the sentence passing the ID of it */
|
||||||
String getFraseFromID(int IDF){
|
public String getFraseFromID(int IDF) {
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
if (IDF == 0) return "No hay más frases disponibles...";
|
||||||
String sentence;
|
if (IDF == -1) return "No puedes ver aún esta frase";
|
||||||
|
if (IDF == -2) return "A ocurrido un error";
|
||||||
if (IDF == 0){return "No hay más frases disponibles...";}
|
try (Cursor c = masterDb.rawQuery("SELECT Frase FROM frases WHERE _id = ?",
|
||||||
else if (IDF == -1){return "No puedes ver aún esta frase";}
|
new String[]{String.valueOf(IDF)})) {
|
||||||
else if (IDF == -2){return "A ocurrido un error";}
|
return c.moveToFirst() ? c.getString(0) : "Error al buscar la frase";
|
||||||
else { //If there is a sentence
|
} catch (Exception e) {
|
||||||
|
Log.e(TAG, "getFrase: " + e);
|
||||||
try {
|
return "Error al buscar la frase";
|
||||||
Cursor c = db.rawQuery("SELECT Frase FROM frases WHERE _id = '" + IDF + "'", null);
|
|
||||||
c.moveToFirst();
|
|
||||||
sentence = c.getString(0);
|
|
||||||
c.close();
|
|
||||||
} catch (Exception e) {
|
|
||||||
Log.e("Database", e.toString());
|
|
||||||
sentence = "Error al buscar la frase";
|
|
||||||
}
|
|
||||||
return sentence;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String getAutorFromID(int IDF){
|
String getAutorFromID(int IDF) {
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
if (IDF <= 0) return "";
|
||||||
String sentence;
|
try (Cursor c = masterDb.rawQuery(
|
||||||
|
"SELECT Autor FROM autores WHERE _id = (SELECT AutorID FROM frases WHERE _id = ?)",
|
||||||
if (IDF <= 0){return "";}
|
new String[]{String.valueOf(IDF)})) {
|
||||||
else { //If there is a sentence
|
return c.moveToFirst() ? c.getString(0) : "";
|
||||||
try {
|
} catch (Exception e) {
|
||||||
Cursor c = db.rawQuery("SELECT Autor FROM autores a WHERE _id=(SELECT AutorID from frases WHERE _id='"+ IDF + "')",null);
|
Log.e(TAG, "getAutor: " + e);
|
||||||
c.moveToFirst();
|
return "";
|
||||||
sentence = c.getString(0);
|
|
||||||
c.close();
|
|
||||||
} catch (Exception e) {
|
|
||||||
Log.e("Database", Objects.requireNonNull(e.getMessage()));
|
|
||||||
sentence = "";
|
|
||||||
}
|
|
||||||
return sentence;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** get fav or a IDFrase */
|
/** get fav of a IDFrase */
|
||||||
Integer getFav(int IDF){
|
Integer getFav(int IDF) {
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
try (Cursor query = userDb.rawQuery("SELECT IDFrase FROM frasesFav WHERE IDFrase = ?",
|
||||||
try{
|
new String[]{String.valueOf(IDF)})) {
|
||||||
Cursor query = db.rawQuery("SELECT IDFrase FROM frasesFav WHERE IDFrase = '"+IDF+"'", null);
|
return query.getCount();
|
||||||
Integer ret = query.getCount(); //There is integer because getCount is
|
} catch (Exception e) {
|
||||||
query.close();
|
Log.e(TAG, "getFav: " + e);
|
||||||
return ret;
|
return 0; // if error, better return not fav
|
||||||
}catch(Exception e){
|
|
||||||
Log.e("Database",e.toString());
|
|
||||||
return 0; //If error, better return not fav
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Add a sentence as favorite */
|
/** Add a sentence as favorite */
|
||||||
void addFav(int IDF){
|
void addFav(int IDF) {
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
ContentValues cv = new ContentValues();
|
||||||
try{
|
cv.put("IDFrase", IDF);
|
||||||
db.execSQL("INSERT INTO frasesFav VALUES('"+IDF+"')");
|
userDb.insertWithOnConflict("frasesFav", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||||
}catch(Exception e){
|
|
||||||
Log.e("Database",e.toString());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Del a favorite sentence */
|
/** Del a favorite sentence */
|
||||||
void delFav(int IDF){
|
void delFav(int IDF) {
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
userDb.delete("frasesFav", "IDFrase = ?", new String[]{String.valueOf(IDF)});
|
||||||
try{
|
|
||||||
db.execSQL("DELETE FROM frasesFav WHERE IDFrase='"+IDF+"'");
|
|
||||||
}catch(Exception e){
|
|
||||||
Log.e("Database",e.toString());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns ID from a day X sentence, if possible */
|
/** Returns ID from a day X sentence, if possible */
|
||||||
int getIDFraseDay(int year,int month,int dayOfMonth){
|
int getIDFraseDay(int year, int month, int dayOfMonth) {
|
||||||
Calendar cal = Calendar.getInstance();
|
|
||||||
try {
|
try {
|
||||||
int ret;
|
String diaArg = String.format(Locale.US, "%04d%02d%02d", year, month, dayOfMonth);
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
|
||||||
|
|
||||||
/* For ever have two digits month and day */
|
/* 1) día ya asignado */
|
||||||
String sYear = Integer.toString(year);
|
try (Cursor c = userDb.rawQuery("SELECT IDFrase FROM frasesG WHERE Tday = ?",
|
||||||
String sMonth = String.format("%02d", month); /* month selected */
|
new String[]{diaArg})) {
|
||||||
String sDay = String.format("%02d", dayOfMonth);/* day selected */
|
if (c.moveToFirst()) {
|
||||||
|
return c.getInt(0);
|
||||||
/* Same for calendar day */
|
}
|
||||||
String cYear = Integer.toString(cal.get(Calendar.YEAR));
|
|
||||||
String cMonth; /* Calendar month */
|
|
||||||
String cDay; /* Calendar day */
|
|
||||||
if ((cal.get(Calendar.MONTH)+1) < 10) {
|
|
||||||
cMonth = "0" + (cal.get(Calendar.MONTH)+1);
|
|
||||||
}else{
|
|
||||||
cMonth = Integer.toString(cal.get(Calendar.MONTH)+1);
|
|
||||||
}
|
|
||||||
if (cal.get(Calendar.DAY_OF_MONTH) < 10) {
|
|
||||||
cDay = "0" + (cal.get(Calendar.DAY_OF_MONTH));
|
|
||||||
}else{
|
|
||||||
cDay = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String diaArg = sYear+sMonth+sDay; //Dia pasado a string yyyymmdd
|
/* 2) futuro: no accesible */
|
||||||
String diaAct = cYear+cMonth+cDay;
|
String today = todayKey();
|
||||||
Cursor query = db.rawQuery("SELECT IDFrase FROM frasesG WHERE Tday = '"+diaArg+"'", null);
|
if (diaArg.compareTo(today) > 0) {
|
||||||
if(query.getCount() != 0) {
|
return -1;
|
||||||
query.moveToFirst();
|
}
|
||||||
ret = query.getInt(0);
|
|
||||||
query.close();
|
/* 3) día pasado sin asignar: solo si la app ya se usó antes de ese día
|
||||||
return ret;
|
(evita backfillar el calendario entero navegando hacia atrás) */
|
||||||
//Else for make sentence if there is today or someday before has a sentence (This is possible if app was installed but not opened)
|
if (diaArg.compareTo(today) < 0) {
|
||||||
}else if ((Integer.decode(diaArg) < Integer.decode(diaAct) && db.rawQuery("SELECT IDFrase FROM frasesG WHERE Tday < '"+diaArg+"'", null).getCount() > 0) || ( Integer.decode(diaArg).equals(Integer.decode(diaAct)) ) ) {
|
try (Cursor c = userDb.rawQuery("SELECT COUNT(*) FROM frasesG WHERE Tday < ?",
|
||||||
//}else{ //Make sentence all times (DEBUG)
|
new String[]{diaArg})) {
|
||||||
try {
|
c.moveToFirst();
|
||||||
query = db.rawQuery("SELECT _id FROM frases WHERE _id NOT IN (SELECT IDFrase FROM frasesG) ORDER BY RANDOM() LIMIT 1", null);
|
if (c.getInt(0) == 0) {
|
||||||
query.moveToFirst();
|
return -1;
|
||||||
db.rawQuery("INSERT INTO frasesG (Tday,IDFrase) VALUES('" + diaArg + "','" + query.getString(0) + "')", null).moveToFirst();
|
}
|
||||||
ret = query.getInt(0);
|
|
||||||
query.close();
|
|
||||||
return ret;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return 0; //0 its no more sentences
|
|
||||||
}
|
|
||||||
}else{ //Not today, do not make one
|
|
||||||
return -1; //-1 its day not accesible now
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 4) asignar frase sin usar */
|
||||||
|
int nuevoId = pickUnusedID();
|
||||||
|
if (nuevoId == 0) {
|
||||||
|
return 0; // no more sentences
|
||||||
|
}
|
||||||
|
ContentValues cv = new ContentValues();
|
||||||
|
cv.put("Tday", diaArg);
|
||||||
|
cv.put("IDFrase", nuevoId);
|
||||||
|
userDb.insertWithOnConflict("frasesG", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||||
|
return nuevoId;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Log.e("Database",e.toString());
|
Log.e(TAG, "getIDFraseDay: " + e);
|
||||||
return -2; //BUG
|
return -2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** ID aleatorio del maestro que aún no se ha asignado a ningún día. 0 si no quedan. */
|
||||||
|
private int pickUnusedID() {
|
||||||
|
Set<Integer> used = new HashSet<>();
|
||||||
|
try (Cursor c = userDb.rawQuery("SELECT IDFrase FROM frasesG", null)) {
|
||||||
|
while (c.moveToNext()) {
|
||||||
|
used.add(c.getInt(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
List<Integer> pool = new ArrayList<>();
|
||||||
|
try (Cursor c = masterDb.rawQuery("SELECT _id FROM frases", null)) {
|
||||||
|
while (c.moveToNext()) {
|
||||||
|
int id = c.getInt(0);
|
||||||
|
if (!used.contains(id)) {
|
||||||
|
pool.add(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pool.isEmpty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return pool.get(new Random().nextInt(pool.size()));
|
||||||
|
}
|
||||||
|
|
||||||
/** Returns ID of today's sentence */
|
/** Returns ID of today's sentence */
|
||||||
Integer getIDFraseHoy(){
|
Integer getIDFraseHoy() {
|
||||||
Calendar cal = Calendar.getInstance();
|
java.util.Calendar cal = java.util.Calendar.getInstance();
|
||||||
//Month + 1 because Android starts with month=0
|
return getIDFraseDay(cal.get(java.util.Calendar.YEAR),
|
||||||
return getIDFraseDay(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH)+1,cal.get(Calendar.DAY_OF_MONTH));
|
cal.get(java.util.Calendar.MONTH) + 1,
|
||||||
|
cal.get(java.util.Calendar.DAY_OF_MONTH));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns an array of favorite IDs */
|
/** Returns an array of favorite IDs */
|
||||||
Integer[] getIDFavs(){
|
Integer[] getIDFavs() {
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
|
||||||
List<Integer> a = new ArrayList<>();
|
List<Integer> a = new ArrayList<>();
|
||||||
|
try (Cursor c = userDb.rawQuery("SELECT IDFrase FROM frasesFav", null)) {
|
||||||
Cursor c = db.rawQuery("SELECT IDFrase FROM frasesFav",null);
|
while (c.moveToNext()) {
|
||||||
|
a.add(c.getInt(0));
|
||||||
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
|
|
||||||
a.add(c.getInt(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
Integer[] Favorites = new Integer[a.size()];
|
|
||||||
a.toArray(Favorites);
|
|
||||||
c.close();
|
|
||||||
return Favorites;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Returns an array of favorite IDs */
|
|
||||||
String[] getAllDaysYet(){
|
|
||||||
SQLiteDatabase db = this.getWritableDatabase();
|
|
||||||
List<String> a = new ArrayList<>();
|
|
||||||
|
|
||||||
Cursor c = db.rawQuery("SELECT Tday FROM frasesG",null);
|
|
||||||
|
|
||||||
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
|
|
||||||
a.add(c.getString(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
String[] Favorites = new String[a.size()];
|
|
||||||
a.toArray(Favorites);
|
|
||||||
c.close();
|
|
||||||
return Favorites;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/* Here Startup of database. When changes, change number up in class */
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onCreate(SQLiteDatabase db) {
|
|
||||||
db.execSQL("CREATE TABLE frases (" +
|
|
||||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
|
||||||
"`Frase` TEXT NOT NULL UNIQUE," +
|
|
||||||
"`AutorID` INTEGER" +
|
|
||||||
")");
|
|
||||||
db.execSQL("CREATE TABLE autores (" +
|
|
||||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
|
||||||
"`Autor` TEXT UNIQUE" +
|
|
||||||
")");
|
|
||||||
db.execSQL("CREATE TABLE frasesG (" +
|
|
||||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
|
||||||
"`Tday` TEXT NOT NULL UNIQUE," +
|
|
||||||
"`IDFrase` INTEGER NOT NULL" +
|
|
||||||
")");
|
|
||||||
db.execSQL("CREATE TABLE frasesFav (" +
|
|
||||||
"`IDFrase` INTEGER NOT NULL UNIQUE" +
|
|
||||||
")");
|
|
||||||
|
|
||||||
String[] queries = readSqldata("Frases").split("\\|");
|
|
||||||
for(String query : queries){
|
|
||||||
db.execSQL(query);
|
|
||||||
}
|
|
||||||
//db.execSQL(readSqldata("Frases"));
|
|
||||||
db.execSQL(readSqldata("Autores"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
|
|
||||||
db.execSQL("DROP TABLE frases");
|
|
||||||
db.execSQL("DROP TABLE autores");
|
|
||||||
db.execSQL("CREATE TABLE frases (" +
|
|
||||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
|
||||||
"`Frase` TEXT NOT NULL UNIQUE," +
|
|
||||||
"`AutorID` INTEGER" +
|
|
||||||
")");
|
|
||||||
db.execSQL("CREATE TABLE autores (" +
|
|
||||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
|
||||||
"`Autor` TEXT UNIQUE" +
|
|
||||||
")");
|
|
||||||
String[] queries = readSqldata("Frases").split("\\|");
|
|
||||||
for(String query : queries){
|
|
||||||
db.execSQL(query);
|
|
||||||
}
|
|
||||||
db.execSQL(readSqldata("Autores"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String readSqldata(String str){
|
|
||||||
//getting the file
|
|
||||||
InputStream inputStream;
|
|
||||||
if (str.equals("Frases")) {
|
|
||||||
inputStream = contextdb.getResources().openRawResource(R.raw.sqlfrases);
|
|
||||||
}else{
|
|
||||||
inputStream = contextdb.getResources().openRawResource(R.raw.sqlautores);
|
|
||||||
}
|
|
||||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
|
||||||
try {
|
|
||||||
int i = inputStream.read();
|
|
||||||
while (i != -1) {
|
|
||||||
byteArrayOutputStream.write(i);
|
|
||||||
i = inputStream.read();
|
|
||||||
}
|
}
|
||||||
inputStream.close();
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
}
|
||||||
return byteArrayOutputStream.toString();
|
return a.toArray(new Integer[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
/** Returns an array of days already assigned (yyyymmdd) */
|
||||||
|
String[] getAllDaysYet() {
|
||||||
|
List<String> a = new ArrayList<>();
|
||||||
|
try (Cursor c = userDb.rawQuery("SELECT Tday FROM frasesG", null)) {
|
||||||
|
while (c.moveToNext()) {
|
||||||
|
a.add(c.getString(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return a.toArray(new String[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String todayKey() {
|
||||||
|
return new SimpleDateFormat("yyyyMMdd", Locale.US).format(new Date());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,11 +26,12 @@ import java.util.HashMap;
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
public class FavsActivity extends AppCompatActivity {
|
public class FavsActivity extends AppCompatActivity {
|
||||||
DatabaseHelper db = new DatabaseHelper(this);
|
DatabaseHelper db;
|
||||||
@Override
|
@Override
|
||||||
protected void onCreate(Bundle savedInstanceState) {
|
protected void onCreate(Bundle savedInstanceState) {
|
||||||
super.onCreate(savedInstanceState);
|
super.onCreate(savedInstanceState);
|
||||||
setContentView(R.layout.activity_favs);
|
setContentView(R.layout.activity_favs);
|
||||||
|
db = new DatabaseHelper(this);
|
||||||
|
|
||||||
final ListView listFavs = (ListView) findViewById(R.id.listSentences);
|
final ListView listFavs = (ListView) findViewById(R.id.listSentences);
|
||||||
|
|
||||||
@@ -84,25 +85,25 @@ public class FavsActivity extends AppCompatActivity {
|
|||||||
@SuppressWarnings("unchecked") /* Because next line has a type change without checking it */
|
@SuppressWarnings("unchecked") /* Because next line has a type change without checking it */
|
||||||
HashMap<String, String> obj = (HashMap<String,String>) listFavs.getItemAtPosition(info.position);
|
HashMap<String, String> obj = (HashMap<String,String>) listFavs.getItemAtPosition(info.position);
|
||||||
|
|
||||||
switch (item.getItemId()) {
|
int id = item.getItemId();
|
||||||
case R.id.copy:
|
if (id == R.id.copy) {
|
||||||
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
|
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
|
||||||
clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", obj.get("item")+this.getString(R.string.sharefrom)));
|
clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", obj.get("item")+this.getString(R.string.sharefrom)));
|
||||||
Toast.makeText(getApplicationContext(), "Copiado al portapapeles", Toast.LENGTH_LONG ).show();
|
Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_LONG ).show();
|
||||||
return true;
|
return true;
|
||||||
case R.id.delfav:
|
} else if (id == R.id.delfav) {
|
||||||
Integer[] IDFavs = db.getIDFavs();
|
Integer[] IDFavs = db.getIDFavs();
|
||||||
db.delFav(IDFavs[info.position]);
|
db.delFav(IDFavs[info.position]);
|
||||||
/* Restart activity for refresh favs */
|
/* Restart activity for refresh favs */
|
||||||
finish();
|
finish();
|
||||||
startActivity(getIntent());
|
startActivity(getIntent());
|
||||||
return true;
|
return true;
|
||||||
case R.id.share:
|
} else if (id == R.id.share) {
|
||||||
Intent intent = new Intent(Intent.ACTION_SEND);
|
Intent intent = new Intent(Intent.ACTION_SEND);
|
||||||
intent.setType("text/plain");
|
intent.setType("text/plain");
|
||||||
intent.putExtra(Intent.EXTRA_TEXT,obj.get("item")+this.getString(R.string.sharefrom));
|
intent.putExtra(Intent.EXTRA_TEXT,obj.get("item")+this.getString(R.string.sharefrom));
|
||||||
startActivity(Intent.createChooser(intent, "Compartir con"));
|
startActivity(Intent.createChooser(intent, getString(R.string.share_with)));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,13 +23,17 @@ import java.util.Calendar;
|
|||||||
import com.google.android.gms.ads.AdRequest;
|
import com.google.android.gms.ads.AdRequest;
|
||||||
import com.google.android.gms.ads.AdView;
|
import com.google.android.gms.ads.AdView;
|
||||||
import com.google.android.gms.ads.MobileAds;
|
import com.google.android.gms.ads.MobileAds;
|
||||||
|
import com.google.android.ump.ConsentInformation;
|
||||||
|
import com.google.android.ump.ConsentRequestParameters;
|
||||||
|
import com.google.android.ump.FormError;
|
||||||
|
import com.google.android.ump.UserMessagingPlatform;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public class MainActivity extends AppCompatActivity implements RobotoCalendarListener {
|
public class MainActivity extends AppCompatActivity implements RobotoCalendarListener {
|
||||||
|
|
||||||
private RobotoCalendarView robotoCalendarView;
|
private RobotoCalendarView robotoCalendarView;
|
||||||
DatabaseHelper db = new DatabaseHelper(this);
|
DatabaseHelper db;
|
||||||
Calendar cal = Calendar.getInstance();
|
Calendar cal = Calendar.getInstance();
|
||||||
Integer IDFrase;
|
Integer IDFrase;
|
||||||
final Config conf = new Config(this);
|
final Config conf = new Config(this);
|
||||||
@@ -56,24 +60,20 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean onOptionsItemSelected(MenuItem item) {
|
public boolean onOptionsItemSelected(MenuItem item) {
|
||||||
switch (item.getItemId()) {
|
int id = item.getItemId();
|
||||||
case R.id.favorites:
|
if (id == R.id.favorites) {
|
||||||
Intent newIF= new Intent(MainActivity.this,FavsActivity.class);
|
startActivity(new Intent(MainActivity.this, FavsActivity.class));
|
||||||
startActivity(newIF);
|
return true;
|
||||||
return true;
|
} else if (id == R.id.options) {
|
||||||
case R.id.options:
|
startActivity(new Intent(MainActivity.this, OptsActivity.class));
|
||||||
Intent newIO= new Intent(MainActivity.this,OptsActivity.class);
|
return true;
|
||||||
startActivity(newIO);
|
} else if (id == R.id.about) {
|
||||||
return true;
|
startActivity(new Intent(MainActivity.this, AboutOfActivity.class));
|
||||||
case R.id.about:
|
return true;
|
||||||
Intent newIA= new Intent(MainActivity.this,AboutOfActivity.class);
|
} else if (id == R.id.exit) {
|
||||||
startActivity(newIA);
|
moveTaskToBack(true); /* Returns to "desktop" */
|
||||||
return true;
|
|
||||||
case R.id.exit:
|
|
||||||
moveTaskToBack(true); /* Returns to "desktop" */
|
|
||||||
default:
|
|
||||||
return super.onOptionsItemSelected(item);
|
|
||||||
}
|
}
|
||||||
|
return super.onOptionsItemSelected(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -83,10 +83,10 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
/* First of all,before loading, see if its the first time using the app */
|
/* First of all,before loading, see if its the first time using the app */
|
||||||
if (conf.getFirstTime()){
|
if (conf.getFirstTime()){
|
||||||
new AlertDialog.Builder(MainActivity.this)
|
new AlertDialog.Builder(MainActivity.this)
|
||||||
.setTitle("Bienvenido")
|
.setTitle(R.string.welcome_title)
|
||||||
.setMessage("Bienvenidos a Calendario de Frases, donde cada día disfrutarás de una nueva cita celebre o de un nuevo refrán que podrás guardar o compartir con tus amigos.\nAdemás, podrás poner una notificación para que te avise de la frase del día a la hora que quieras, por ejemplo, al desperarte.\nRecuerda que no puedes ver frases de los días que no hayan pasado aún con la aplicación.\nEsperamos que la disfrutes.")
|
.setMessage(R.string.welcome_text)
|
||||||
.setCancelable(false)
|
.setCancelable(false)
|
||||||
.setPositiveButton("Empecemos", new DialogInterface.OnClickListener() {
|
.setPositiveButton(R.string.welcome_button, new DialogInterface.OnClickListener() {
|
||||||
@Override
|
@Override
|
||||||
public void onClick(DialogInterface dialog, int which) {
|
public void onClick(DialogInterface dialog, int which) {
|
||||||
// Nothing
|
// Nothing
|
||||||
@@ -96,6 +96,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
}
|
}
|
||||||
|
|
||||||
setContentView(R.layout.activity_main);
|
setContentView(R.layout.activity_main);
|
||||||
|
db = new DatabaseHelper(this);
|
||||||
txtfraseTitle = findViewById(R.id.txt_frasetitle);
|
txtfraseTitle = findViewById(R.id.txt_frasetitle);
|
||||||
txtfraseText = findViewById(R.id.txt_frasetext);
|
txtfraseText = findViewById(R.id.txt_frasetext);
|
||||||
txtfraseAutor = findViewById(R.id.txt_fraseautor);
|
txtfraseAutor = findViewById(R.id.txt_fraseautor);
|
||||||
@@ -108,20 +109,46 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
robotoCalendarView.setShortWeekDays(false);
|
robotoCalendarView.setShortWeekDays(false);
|
||||||
robotoCalendarView.showDateTitle(true);
|
robotoCalendarView.showDateTitle(true);
|
||||||
|
|
||||||
/* Admob ads */
|
/* Admob ads: consentimiento UMP primero, luego init en background y banner */
|
||||||
MobileAds.initialize(getApplicationContext());
|
setUpConsentAndAds();
|
||||||
AdView mAdView = (AdView) findViewById(R.id.adView);
|
|
||||||
AdRequest adRequest = new AdRequest.Builder().build();
|
|
||||||
mAdView.loadAd(adRequest); //request a new ad
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/* Configure alarm */
|
|
||||||
Alarm alarm = new Alarm();
|
|
||||||
alarm.putAlarm(this);
|
|
||||||
|
|
||||||
/* Register context menu */
|
/* Register context menu */
|
||||||
registerForContextMenu(txtfraseText);
|
registerForContextMenu(txtfraseText);
|
||||||
|
|
||||||
|
/* Close app on back button */
|
||||||
|
getOnBackPressedDispatcher().addCallback(this, new androidx.activity.OnBackPressedCallback(true) {
|
||||||
|
@Override
|
||||||
|
public void handleOnBackPressed() {
|
||||||
|
moveTaskToBack(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Consentimiento UMP (obligatorio EEA) y tras él, init de AdMob + banner */
|
||||||
|
private void setUpConsentAndAds() {
|
||||||
|
ConsentRequestParameters params = new ConsentRequestParameters.Builder().build();
|
||||||
|
ConsentInformation consentInfo = UserMessagingPlatform.getConsentInformation(this);
|
||||||
|
consentInfo.requestConsentInfoUpdate(
|
||||||
|
this,
|
||||||
|
params,
|
||||||
|
() -> UserMessagingPlatform.loadAndShowConsentFormIfRequired(
|
||||||
|
this,
|
||||||
|
formError -> initAdsAfterConsent()),
|
||||||
|
formError -> initAdsAfterConsent());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initAdsAfterConsent() {
|
||||||
|
/* MobileAds.initialize en background: no bloquee el arranque */
|
||||||
|
new Thread(() -> {
|
||||||
|
MobileAds.initialize(getApplicationContext());
|
||||||
|
runOnUiThread(() -> {
|
||||||
|
AdView mAdView = findViewById(R.id.adView);
|
||||||
|
AdRequest adRequest = new AdRequest.Builder().build();
|
||||||
|
mAdView.loadAd(adRequest);
|
||||||
|
});
|
||||||
|
}).start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -150,7 +177,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
public void onClick(View viewIn) {
|
public void onClick(View viewIn) {
|
||||||
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
|
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
|
||||||
clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", txtfraseText.getText()+MainActivity.this.getString(R.string.sharefrom)));
|
clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", txtfraseText.getText()+MainActivity.this.getString(R.string.sharefrom)));
|
||||||
Toast.makeText(getApplicationContext(), "Copiado al portapapeles", Toast.LENGTH_LONG ).show();
|
Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_LONG ).show();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
changeFavImage(); //Fav image button
|
changeFavImage(); //Fav image button
|
||||||
@@ -175,7 +202,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
Intent intent = new Intent(Intent.ACTION_SEND);
|
Intent intent = new Intent(Intent.ACTION_SEND);
|
||||||
intent.setType("text/plain");
|
intent.setType("text/plain");
|
||||||
intent.putExtra(Intent.EXTRA_TEXT, sentence+MainActivity.this.getString(R.string.sharefrom));
|
intent.putExtra(Intent.EXTRA_TEXT, sentence+MainActivity.this.getString(R.string.sharefrom));
|
||||||
startActivity(Intent.createChooser(intent, "Compartir con"));
|
startActivity(Intent.createChooser(intent, getString(R.string.share_with)));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -189,12 +216,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* Close app on back button */
|
/* Close app on back button: registrado en onCreate con OnBackPressedDispatcher */
|
||||||
@Override
|
|
||||||
public void onBackPressed()
|
|
||||||
{
|
|
||||||
moveTaskToBack(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -211,7 +233,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
|||||||
txtfraseAutor.setText(db.getAutorFromID(IDFrase));
|
txtfraseAutor.setText(db.getAutorFromID(IDFrase));
|
||||||
/* Set Title before sentence */
|
/* Set Title before sentence */
|
||||||
if (year != cal.get(Calendar.YEAR) || month != (cal.get(Calendar.MONTH)+1) || day != cal.get(Calendar.DAY_OF_MONTH)) {
|
if (year != cal.get(Calendar.YEAR) || month != (cal.get(Calendar.MONTH)+1) || day != cal.get(Calendar.DAY_OF_MONTH)) {
|
||||||
txtfraseTitle.setText("Frase del " + day + " de " + getMonth(month)); //Change title
|
txtfraseTitle.setText(getString(R.string.sentence_of_day, day, getMonth(month))); //Change title
|
||||||
}else {
|
}else {
|
||||||
txtfraseTitle.setText(R.string.txt_todaysentence); //Change title (today)
|
txtfraseTitle.setText(R.string.txt_todaysentence); //Change title (today)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
package com.jkanetwork.st.calendariodefrases;
|
||||||
|
|
||||||
import android.app.NotificationManager;
|
import android.Manifest;
|
||||||
import android.content.Intent;
|
import android.content.pm.PackageManager;
|
||||||
|
import android.os.Build;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
import androidx.appcompat.app.AppCompatActivity;
|
import androidx.appcompat.app.AppCompatActivity;
|
||||||
|
import androidx.core.app.ActivityCompat;
|
||||||
|
import androidx.core.content.ContextCompat;
|
||||||
import android.view.View;
|
import android.view.View;
|
||||||
import android.widget.ArrayAdapter;
|
import android.widget.ArrayAdapter;
|
||||||
import android.widget.Button;
|
import android.widget.Button;
|
||||||
@@ -99,19 +102,31 @@ public class OptsActivity extends AppCompatActivity {
|
|||||||
conf.setNotifOn(chkalarm.isChecked());
|
conf.setNotifOn(chkalarm.isChecked());
|
||||||
conf.setPersistNotifOn(chkpersistent.isChecked());
|
conf.setPersistNotifOn(chkpersistent.isChecked());
|
||||||
|
|
||||||
/* Cancel notif when save changes first */
|
if (chkalarm.isChecked() && !notificationsEnabled()) {
|
||||||
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
|
/* Android 13+: pedir permiso para poder mostrar la notificación */
|
||||||
nm.cancel(1);
|
ActivityCompat.requestPermissions(OptsActivity.this,
|
||||||
|
new String[]{Manifest.permission.POST_NOTIFICATIONS}, 1);
|
||||||
|
}
|
||||||
|
|
||||||
Alarm alarm = new Alarm();
|
/* Cancel notif when save changes first */
|
||||||
alarm.putAlarm(OptsActivity.this);
|
Notif.cancel(OptsActivity.this);
|
||||||
|
|
||||||
|
NotifScheduler.schedule(OptsActivity.this);
|
||||||
if (chkpersistent.isChecked() && chkalarm.isChecked()) {
|
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(){
|
public void setEnabledParts(){
|
||||||
/* I have to set vars again because is out of onCreate */
|
/* I have to set vars again because is out of onCreate */
|
||||||
Spinner notifHour = findViewById(R.id.spinnerHour);
|
Spinner notifHour = findViewById(R.id.spinnerHour);
|
||||||
|
|||||||
@@ -72,8 +72,8 @@
|
|||||||
android:layout_gravity="top"
|
android:layout_gravity="top"
|
||||||
android:layout_marginTop="8dp"
|
android:layout_marginTop="8dp"
|
||||||
android:layout_weight="1"
|
android:layout_weight="1"
|
||||||
|
android:gravity="end"
|
||||||
android:text="(Aqui autor)"
|
android:text="(Aqui autor)"
|
||||||
android:textAlignment="textEnd"
|
|
||||||
android:textColor="#222" />
|
android:textColor="#222" />
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,15 @@
|
|||||||
<string name="favorites">Favoritos</string>
|
<string name="favorites">Favoritos</string>
|
||||||
<string name="options">Opciones</string>
|
<string name="options">Opciones</string>
|
||||||
<string name="aboutOf">Acerca de</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>
|
||||||
|
<string name="welcome_title">Bienvenido</string>
|
||||||
|
<string name="welcome_text">Bienvenidos a Calendario de Frases, donde cada día disfrutarás de una nueva cita celebre o de un nuevo refrán que podrás guardar o compartir con tus amigos.\nAdemás, podrás poner una notificación para que te avise de la frase del día a la hora que quieras, por ejemplo, al desperarte.\nRecuerda que no puedes ver frases de los días que no hayan pasado aún con la aplicación.\nEsperamos que la disfrutes.</string>
|
||||||
|
<string name="welcome_button">Empecemos</string>
|
||||||
|
<string name="copied">Copiado al portapapeles</string>
|
||||||
|
<string name="share_with">Compartir con</string>
|
||||||
|
<string name="sentence_of_day">Frase del %1$d de %2$s</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.jkanetwork.st.calendariodefrases;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests de las partes de lógica pura (sin Android framework).
|
||||||
|
*/
|
||||||
|
public class DayKeyTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void todayKey_formato_yyyymmdd() {
|
||||||
|
String key = new SimpleDateFormat("yyyyMMdd", Locale.US).format(new Date());
|
||||||
|
Calendar cal = Calendar.getInstance();
|
||||||
|
String expected = String.format(Locale.US, "%04d%02d%02d",
|
||||||
|
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH));
|
||||||
|
assertEquals(expected, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void dayKey_comparacionLexicografica_funcionaComoFecha() {
|
||||||
|
// La lógica de getIDFraseDay compara diaArg vs hoy como strings: debe
|
||||||
|
// mantenerse el orden cronológico.
|
||||||
|
assertTrue("20261020".compareTo("20261019") > 0);
|
||||||
|
assertTrue("20261101".compareTo("20261031") > 0);
|
||||||
|
assertTrue("20270101".compareTo("20261231") > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void assertTrue(boolean b) {
|
||||||
|
org.junit.Assert.assertTrue(b);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package com.jkanetwork.st.calendariodefrases;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Example local unit test, which will execute on the development machine (host).
|
|
||||||
*
|
|
||||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
|
||||||
*/
|
|
||||||
public class ExampleUnitTest {
|
|
||||||
@Test
|
|
||||||
public void addition_isCorrect() throws Exception {
|
|
||||||
assertEquals(4, 2 + 2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+2
-2
@@ -1,2 +1,2 @@
|
|||||||
#Sun Apr 07 14:20:00 CEST 2024
|
#Tue Oct 20 13:03:03 UTC 2026
|
||||||
VERSION_CODE=353
|
VERSION_CODE=378
|
||||||
+2
-26
@@ -1,28 +1,4 @@
|
|||||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||||
|
plugins {
|
||||||
buildscript {
|
id 'com.android.application' version '9.4.1' apply false
|
||||||
repositories {
|
|
||||||
mavenCentral()
|
|
||||||
google()
|
|
||||||
}
|
|
||||||
dependencies {
|
|
||||||
classpath 'com.android.tools.build:gradle:8.3.0'
|
|
||||||
|
|
||||||
|
|
||||||
// NOTE: Do not place your application dependencies here; they belong
|
|
||||||
// in the individual module build.gradle files
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
allprojects {
|
|
||||||
repositories {
|
|
||||||
mavenCentral()
|
|
||||||
maven { url 'https://jitpack.io' }
|
|
||||||
google()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
tasks.register('clean', Delete) {
|
|
||||||
delete rootProject.buildDir
|
|
||||||
}
|
}
|
||||||
+5
-17
@@ -1,21 +1,9 @@
|
|||||||
# Project-wide Gradle settings.
|
# Project-wide Gradle settings.
|
||||||
|
|
||||||
# IDE (e.g. Android Studio) users:
|
# JVM arguments for the daemon process.
|
||||||
# Gradle settings configured through the IDE *will override*
|
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||||
# any settings specified in this file.
|
|
||||||
|
|
||||||
# For more details on how to configure your build environment visit
|
# AndroidX
|
||||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
|
||||||
|
|
||||||
# Specifies the JVM arguments used for the daemon process.
|
|
||||||
# The setting is particularly useful for tweaking memory settings.
|
|
||||||
android.enableJetifier=true
|
|
||||||
android.nonFinalResIds=false
|
|
||||||
android.nonTransitiveRClass=false
|
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
org.gradle.jvmargs=-Xmx1536m
|
# Necesario mientras se use robotocalendarview (lib pre-AndroidX, se jetifica en build)
|
||||||
|
android.enableJetifier=true
|
||||||
# When configured, Gradle will run in incubating parallel mode.
|
|
||||||
# This option should only be used with decoupled projects. More details, visit
|
|
||||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
|
||||||
# org.gradle.parallel=true
|
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
@@ -1 +1,16 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
maven { url 'https://jitpack.io' }
|
||||||
|
}
|
||||||
|
}
|
||||||
include ':app'
|
include ':app'
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Genera app/src/main/assets/frases.db (BD maestra) desde res/raw.
|
||||||
|
|
||||||
|
Fuente de verdad: res/raw/sqlfrases y res/raw/sqlautores (INSERTs).
|
||||||
|
Los IDs se respetan (mismo orden de inserción), por eso los favoritos y
|
||||||
|
días históricos de la BD de usuario sobreviven a las actualizaciones.
|
||||||
|
|
||||||
|
Al añadir/cambiar frases: editar los raw y subir MASTER_DB_VERSION
|
||||||
|
(la app recopia el maestro cuando el user_version del asset es mayor).
|
||||||
|
|
||||||
|
Uso: python3 tools/build_master_db.py
|
||||||
|
"""
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
RAW = ROOT / "app/src/main/res/raw"
|
||||||
|
OUT = ROOT / "app/src/main/assets/frases.db"
|
||||||
|
|
||||||
|
# Subir al cambiar el contenido de frases/autores
|
||||||
|
MASTER_DB_VERSION = 1
|
||||||
|
|
||||||
|
SCHEMA = """
|
||||||
|
CREATE TABLE frases (
|
||||||
|
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
`Frase` TEXT NOT NULL UNIQUE,
|
||||||
|
`AutorID` INTEGER
|
||||||
|
);
|
||||||
|
CREATE TABLE autores (
|
||||||
|
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
`Autor` TEXT UNIQUE
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def load_statements(path: Path) -> list[str]:
|
||||||
|
# Los raw separan statements con '|', igual que hacía DatabaseHelper.onCreate
|
||||||
|
return [s.strip() for s in path.read_text(encoding="utf-8").split("|") if s.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if OUT.exists():
|
||||||
|
OUT.unlink()
|
||||||
|
con = sqlite3.connect(OUT)
|
||||||
|
try:
|
||||||
|
con.executescript(SCHEMA)
|
||||||
|
for stmt in load_statements(RAW / "sqlfrases"):
|
||||||
|
con.execute(stmt)
|
||||||
|
for stmt in load_statements(RAW / "sqlautores"):
|
||||||
|
con.execute(stmt)
|
||||||
|
con.execute(f"PRAGMA user_version = {MASTER_DB_VERSION}")
|
||||||
|
con.commit()
|
||||||
|
n_frases = con.execute("SELECT COUNT(*) FROM frases").fetchone()[0]
|
||||||
|
n_autores = con.execute("SELECT COUNT(*) FROM autores").fetchone()[0]
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
print(f"OK {OUT}: {n_frases} frases, {n_autores} autores, user_version={MASTER_DB_VERSION}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
Reference in new issue
Block a user