Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions android/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ android {
applicationId = "space.gitwall.app"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "1.0.0"
versionCode = 2
versionName = "1.1.0"
}

signingConfigs {
Expand Down
2 changes: 2 additions & 0 deletions android/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
# WorkManager instantiates workers reflectively by class name.
-keep class space.gitwall.app.RefreshWorker { *; }
-keep class space.gitwall.app.AlarmReceiver { *; }
-keep class space.gitwall.app.BootReceiver { *; }
20 changes: 20 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Exact daily alarm. Granted at install on Android 12 and below; on 13+
USE_EXACT_ALARM is the install-time variant for apps whose core
feature is a user-chosen time, which is exactly this app. -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
<!-- Lets the app open the "unrestricted battery" dialog for itself, so the
network is reachable when the alarm fires during deep sleep. -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

<application
android:allowBackup="false"
Expand Down Expand Up @@ -36,5 +45,16 @@
<data android:mimeType="text/plain" />
</intent-filter>
</activity>

<receiver android:name=".AlarmReceiver" android:exported="false" />

<receiver android:name=".BootReceiver" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
86 changes: 86 additions & 0 deletions android/app/src/main/java/space/gitwall/app/DailyAlarm.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package space.gitwall.app

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import java.util.Calendar

/**
* One exact alarm per day at the user's chosen time. Exact alarms fire within
* a minute even while the phone sleeps, unlike WorkManager's batched jobs that
* Android may hold back for hours overnight. The alarm only enqueues the
* worker; the download itself runs under WorkManager with its retries.
*/
object DailyAlarm {
private const val REQUEST_CODE = 1001

fun arm(context: Context, hour: Int, minute: Int) {
val at = System.currentTimeMillis() + millisUntil(hour, minute)
val alarms = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pending = pendingIntent(context)
val exact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarms.canScheduleExactAlarms()
if (exact) {
alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)
} else {
// Exact alarms were revoked by the user; land as close as Android allows.
alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)
}
SettingsStore(context).saveNextRun(at)
}

fun cancel(context: Context) {
val alarms = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarms.cancel(pendingIntent(context))
SettingsStore(context).saveNextRun(0L)
}

fun millisUntil(hour: Int, minute: Int): Long {
val now = Calendar.getInstance()
val next = (now.clone() as Calendar).apply {
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
if (!after(now)) add(Calendar.DAY_OF_YEAR, 1)
}
return next.timeInMillis - now.timeInMillis
}

private fun pendingIntent(context: Context): PendingIntent =
PendingIntent.getBroadcast(
context,
REQUEST_CODE,
Intent(context, AlarmReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
}

class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val settings = SettingsStore(context).read()
if (settings.url.isBlank()) return
// Re-arm first so a crash in the refresh can never lose tomorrow's alarm.
DailyAlarm.arm(context, settings.refreshHour, settings.refreshMinute)
Scheduler.runNow(context, RefreshWorker.SOURCE_ALARM)
}
}

/** Alarms are cleared on reboot and can drift on clock or zone changes; re-arm and catch up. */
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_MY_PACKAGE_REPLACED,
Intent.ACTION_TIME_CHANGED,
Intent.ACTION_TIMEZONE_CHANGED -> {
val settings = SettingsStore(context).read()
if (settings.url.isBlank()) return
DailyAlarm.arm(context, settings.refreshHour, settings.refreshMinute)
Scheduler.ensureHealthy(context)
}
}
}
}
82 changes: 75 additions & 7 deletions android/app/src/main/java/space/gitwall/app/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package space.gitwall.app

import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings as AndroidSettings
import android.text.format.DateFormat
import android.text.format.DateUtils
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
Expand All @@ -16,9 +21,11 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
Expand All @@ -31,6 +38,7 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
Expand All @@ -42,9 +50,13 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext

import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.work.WorkInfo
import androidx.work.WorkManager
Expand All @@ -56,7 +68,9 @@ private val Ink = Color(0xFF0A0A0A)
private val Panel = Color(0xFF141414)
private val Line = Color(0xFF2A2A2A)
private val Muted = Color(0xFF8B8B8B)
private val Dim = Color(0xFF555555)
private val Danger = Color(0xFFF87171)
private val Amber = Color(0xFFF5C451)

class MainActivity : ComponentActivity() {
private val incomingUrl = mutableStateOf<String?>(null)
Expand All @@ -83,6 +97,11 @@ class MainActivity : ComponentActivity() {
extractWallpaperUrl(intent?.data, intent?.getStringExtra(Intent.EXTRA_TEXT))
}

private fun isBatteryUnrestricted(context: Context): Boolean {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return pm.isIgnoringBatteryOptimizations(context.packageName)
}

@Composable
private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) {
val context = LocalContext.current
Expand All @@ -95,9 +114,24 @@ private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) {

var url by remember { mutableStateOf(settings.url) }
var validation by remember { mutableStateOf<String?>(null) }
var batteryOk by remember { mutableStateOf(isBatteryUnrestricted(context)) }
val clipboard = LocalClipboardManager.current
val size = remember { screenSize(context) }

// Every time the screen comes back: re-check the battery setting (the user
// may have just changed it) and catch up if a refresh was missed.
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
batteryOk = isBatteryUnrestricted(context)
Scheduler.ensureHealthy(context)
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}

// A URL handed over by the website replaces whatever is in the field.
LaunchedEffect(incomingUrl) {
if (incomingUrl != null) {
Expand All @@ -124,7 +158,6 @@ private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) {
context,
{ _, hour, minute ->
store.saveRefreshTime(hour, minute)
// Only re-anchor the schedule when a wallpaper is already set up.
if (settings.url.isNotBlank()) Scheduler.scheduleDaily(context, hour, minute)
},
settings.refreshHour,
Expand All @@ -133,10 +166,17 @@ private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) {
).show()
}

fun requestUnrestrictedBattery() {
val intent = Intent(AndroidSettings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:${context.packageName}"))
runCatching { context.startActivity(intent) }
.onFailure { context.startActivity(Intent(AndroidSettings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) }
}

Column(
Modifier
.fillMaxSize()
.statusBarsPadding()
.navigationBarsPadding()
.verticalScroll(rememberScrollState())
.padding(horizontal = 24.dp, vertical = 32.dp),
) {
Expand All @@ -154,7 +194,7 @@ private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) {
value = url,
onValueChange = { url = it; validation = null },
modifier = Modifier.fillMaxWidth(),
placeholder = { Text("https://gitwall.space/api/wallpaper?user=...", color = Color(0xFF555555)) },
placeholder = { Text("https://gitwall.space/api/wallpaper?user=...", color = Dim) },
singleLine = false,
minLines = 2,
isError = validation != null,
Expand Down Expand Up @@ -189,32 +229,60 @@ private fun Screen(incomingUrl: String?, onIncomingConsumed: () -> Unit) {
}
}

if (!batteryOk) {
Spacer(Modifier.height(12.dp))
Column(
Modifier
.fillMaxWidth()
.background(Color(0xFF1A1709), RoundedCornerShape(10.dp))
.padding(14.dp),
) {
Text("Allow background refresh", color = Amber, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.height(4.dp))
Text(
"Android pauses this app's network while the phone sleeps, so the daily refresh may run hours late or not at all. Set battery use to Unrestricted to fix that.",
color = Color(0xFFBFB08A), fontSize = 12.sp, lineHeight = 17.sp,
)
TextButton(onClick = ::requestUnrestrictedBattery, contentPadding = PaddingValues(0.dp)) {
Text("Allow", color = Amber, fontSize = 13.sp, fontWeight = FontWeight.Bold)
}
}
}

Spacer(Modifier.height(16.dp))
Status(settings, size)
}
}

private fun formatTime(context: android.content.Context, hour: Int, minute: Int): String {
private fun formatTime(context: Context, hour: Int, minute: Int): String {
val cal = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hour)
set(Calendar.MINUTE, minute)
}
return DateFormat.getTimeFormat(context).format(cal.time)
}

private fun formatWhen(context: Context, at: Long): String =
DateUtils.formatDateTime(context, at, DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_ALL)

@Composable
private fun Status(settings: Settings, size: ScreenSize) {
val context = LocalContext.current
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
when {
settings.lastError != null -> Text(settings.lastError, color = Danger, fontSize = 13.sp, lineHeight = 18.sp)
settings.lastError != null -> Text(
"Last attempt " + DateUtils.getRelativeTimeSpanString(settings.lastAttemptAt).toString().lowercase() + " failed: " + settings.lastError,
color = Danger, fontSize = 13.sp, lineHeight = 18.sp,
)
settings.lastSuccessAt > 0L -> Text(
"Lock screen updated " + DateUtils.getRelativeTimeSpanString(settings.lastSuccessAt).toString().lowercase() +
". Next refresh around " + formatTime(context, settings.refreshHour, settings.refreshMinute) + ".",
"Lock screen updated " + DateUtils.getRelativeTimeSpanString(settings.lastSuccessAt).toString().lowercase() + ".",
color = Green, fontSize = 13.sp, lineHeight = 18.sp,
)
else -> Text("Not set yet.", color = Muted, fontSize = 13.sp)
}
Text("This phone renders at ${size.width} x ${size.height}.", color = Color(0xFF555555), fontSize = 12.sp)
if (settings.nextRunAt > 0L) {
Text("Next refresh: " + formatWhen(context, settings.nextRunAt), color = Muted, fontSize = 12.sp)
}
Text("This phone renders at ${size.width} x ${size.height}.", color = Dim, fontSize = 12.sp)
}
}
Loading
Loading