Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 5 additions & 4 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@

<!-- Required for Android 11+ (API 30) to see these packages -->
<queries>
<!-- Default launcher: excluded from screen time -->
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
</intent>
<!-- Weather Apps -->
<package android:name="org.breezyweather" />

Expand Down Expand Up @@ -73,13 +78,9 @@
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<action android:name="android.intent.action.CONFIGURATION_CHANGED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.leanbitlab.lwidget.ACTION_BATTERY_UPDATE" />
<action android:name="com.leanbitlab.lwidget.ACTION_STEP_UPDATE" />
<action android:name="android.app.action.NEXT_ALARM_CLOCK_CHANGED" />
<action android:name="nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER" />
</intent-filter>
Expand Down
23 changes: 15 additions & 8 deletions app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import com.leanbitlab.lwidget.calendar.CalendarFetcher
import com.leanbitlab.lwidget.render.WidgetRenderer
import com.leanbitlab.lwidget.stats.SystemStatsFetcher
import com.leanbitlab.lwidget.tasks.TasksFetcher
import com.leanbitlab.lwidget.weather.BreezyWeatherFetcher
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -104,13 +105,15 @@ class AwidgetProvider : AppWidgetProvider() {
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)

val appWidgetManager = AppWidgetManager.getInstance(context)
val thisAppWidget = ComponentName(context, AwidgetProvider::class.java)
val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget)
// Weather arrives only through this broadcast: persist it before rendering
if (intent.action == ACTION_GENERIC_WEATHER) {
val weatherJson = intent.getStringExtra(EXTRA_WEATHER_JSON)
if (weatherJson.isNullOrEmpty()) return
BreezyWeatherFetcher.saveLatestWeatherData(context, weatherJson)
}

val isBootOrReplaced = intent.action in listOf(
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_LOCKED_BOOT_COMPLETED,
Intent.ACTION_MY_PACKAGE_REPLACED,
"android.intent.action.QUICKBOOT_POWERON",
"com.htc.intent.action.QUICKBOOT_POWERON"
Expand All @@ -122,16 +125,17 @@ class AwidgetProvider : AppWidgetProvider() {
}

if (isBootOrReplaced || intent.action in listOf(
Intent.ACTION_CONFIGURATION_CHANGED,
ACTION_BATTERY_UPDATE,
StepCounterService.ACTION_STEP_UPDATE,
Intent.ACTION_PROVIDER_CHANGED,
AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED,
"nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER"
ACTION_GENERIC_WEATHER
)) {
runAsync("broadcast ${intent.action}") {
val appWidgetManager = AppWidgetManager.getInstance(context)
val appWidgetIds = appWidgetManager.getAppWidgetIds(ComponentName(context, AwidgetProvider::class.java))
when {
isBootOrReplaced || intent.action == Intent.ACTION_CONFIGURATION_CHANGED -> {
isBootOrReplaced -> {
scheduleWork(context)
appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) }
}
Expand All @@ -152,7 +156,7 @@ class AwidgetProvider : AppWidgetProvider() {
appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.CALENDAR_ONLY) }
}
}
intent.action == "nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER" -> {
intent.action == ACTION_GENERIC_WEATHER -> {
appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) }
}
}
Expand Down Expand Up @@ -210,6 +214,9 @@ class AwidgetProvider : AppWidgetProvider() {
}

const val ACTION_NOOP = "com.leanbitlab.lwidget.ACTION_NOOP"
/** Gadgetbridge weather broadcast sent by Breezy Weather; payload is the JSON extra. */
const val ACTION_GENERIC_WEATHER = "nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER"
const val EXTRA_WEATHER_JSON = "WeatherJson"
const val ACTION_BATTERY_UPDATE = SystemStatsFetcher.ACTION_BATTERY_UPDATE
const val PERMISSION_READ_TASKS_ORG = TasksFetcher.PERMISSION_READ_TASKS_ORG
const val PERMISSION_READ_TASKS_ASTRID = TasksFetcher.PERMISSION_READ_TASKS_ASTRID
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ class MainActivity : AppCompatActivity() {
updateWidget()
updateToggleAvailability()
}
} else if (requestCode == REQUEST_KEEP_ALIVE_PERMISSIONS) {
onKeepAlivePermissionsResult()
} else if (requestCode == 103) {
// Breezy Weather permission result
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Expand Down
26 changes: 22 additions & 4 deletions app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,13 @@ internal fun MainActivity.setupKeepAliveSection() {
.edit().putBoolean("keep_alive", isChecked).apply()

if (isChecked) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 105)
val missing = StepCounterService.missingKeepAlivePermissions(this)
if (missing.isNotEmpty()) {
// Service starts (or the switch reverts) in onRequestPermissionsResult
ActivityCompat.requestPermissions(this, missing, REQUEST_KEEP_ALIVE_PERMISSIONS)
} else {
StepCounterService.startServiceIfEnabled(this)
}
StepCounterService.startServiceIfEnabled(this)
} else {
if (!StepCounterService.isStepOrKeepAliveEnabled(this)) {
stopService(Intent(this, StepCounterService::class.java))
Expand All @@ -204,6 +206,22 @@ internal fun MainActivity.setupKeepAliveSection() {
}
}

internal const val REQUEST_KEEP_ALIVE_PERMISSIONS = 105

/** After the keep-alive permission prompt: start the service, or turn keep-alive off if it cannot run. */
internal fun MainActivity.onKeepAlivePermissionsResult() {
if (StepCounterService.canStart(this)) {
StepCounterService.startServiceIfEnabled(this)
return
}
prefs.edit().putBoolean("keep_alive", false).apply()
getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
.edit().putBoolean("keep_alive", false).apply()
findViewById<View>(R.id.row_keep_alive_toggle)
?.findViewById<com.google.android.material.switchmaterial.SwitchMaterial>(R.id.row_switch)?.isChecked = false
android.widget.Toast.makeText(this, R.string.msg_keep_alive_needs_activity, android.widget.Toast.LENGTH_LONG).show()
}

internal fun MainActivity.setupBatteryOptimizationSection() {
val row = findViewById<View>(R.id.row_battery_optimization_toggle)
val tvTitle = row.findViewById<TextView>(R.id.row_label)
Expand Down
13 changes: 8 additions & 5 deletions app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ class SetupActivity : AppCompatActivity() {
ActivityResultContracts.RequestMultiplePermissions()
) { _ ->
updatePermissionButtons()
// Keep-alive cannot run without its permissions (Android 14+): revert the switch
if (prefs.getBoolean("keep_alive", false) && !StepCounterService.canStart(this)) {
findViewById<SwitchMaterial>(R.id.switch_setup_keep_alive).isChecked = false
android.widget.Toast.makeText(this, R.string.msg_keep_alive_needs_activity, android.widget.Toast.LENGTH_LONG).show()
}
}

override fun onCreate(savedInstanceState: Bundle?) {
Expand Down Expand Up @@ -76,13 +81,11 @@ class SetupActivity : AppCompatActivity() {
val switchKeepAlive = findViewById<SwitchMaterial>(R.id.switch_setup_keep_alive)
switchKeepAlive.isChecked = prefs.getBoolean("keep_alive", false)
switchKeepAlive.setOnCheckedChangeListener { _, isChecked ->
prefs.edit().putBoolean("keep_alive", isChecked).apply()
if (isChecked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
requestPermissionLauncher.launch(arrayOf(Manifest.permission.POST_NOTIFICATIONS))
}
val missing = StepCounterService.missingKeepAlivePermissions(this)
if (missing.isNotEmpty()) requestPermissionLauncher.launch(missing)
}
prefs.edit().putBoolean("keep_alive", isChecked).apply()
}

// Permissions Setup
Expand Down
56 changes: 29 additions & 27 deletions app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -113,22 +113,36 @@ class StepCounterService : Service(), SensorEventListener {
return false
}

fun startServiceIfEnabled(context: Context) {
if (!isStepOrKeepAliveEnabled(context)) return

val showSteps = isStepsVisibleAnywhere(context)
val hasActivityPerm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
private fun hasActivityPermission(context: Context): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ||
ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACTIVITY_RECOGNITION) == android.content.pm.PackageManager.PERMISSION_GRANTED
} else {
true
}

// If only steps are enabled and activity permission is missing, do not start
if (showSteps && !hasActivityPerm) {
val globalPrefs = context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
val keepAlive = globalPrefs.getBoolean("keep_alive", false)
if (!keepAlive) return
/**
* Whether the foreground service may run. It uses the health FGS type, which Android 14+
* refuses without ACTIVITY_RECOGNITION (SecurityException), even for keep-alive alone.
* Before 14, keep-alive can run without it; steps never can.
*/
fun canStart(context: Context): Boolean {
if (!isStepOrKeepAliveEnabled(context)) return false
if (hasActivityPermission(context)) return true
val keepAlive = context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE)
.getBoolean("keep_alive", false)
return keepAlive && Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE
}

/** Runtime permissions still missing for keep-alive's foreground service. */
fun missingKeepAlivePermissions(context: Context): Array<String> = buildList {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
add(android.Manifest.permission.POST_NOTIFICATIONS)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !hasActivityPermission(context)) {
add(android.Manifest.permission.ACTIVITY_RECOGNITION)
}
}.toTypedArray()

fun startServiceIfEnabled(context: Context) {
if (!canStart(context)) return

try {
val serviceIntent = Intent(context, StepCounterService::class.java)
Expand Down Expand Up @@ -161,22 +175,11 @@ class StepCounterService : Service(), SensorEventListener {
return
}

val showSteps = isStepsVisibleAnywhere(this)
val isNeeded = isStepOrKeepAliveEnabled(this)

// If steps is explicitly enabled, require ACTIVITY_RECOGNITION
val hasActivityPerm = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACTIVITY_RECOGNITION) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (showSteps && !hasActivityPerm) {
val keepAlive = prefs.getBoolean("keep_alive", false)
if (!keepAlive) {
stopSelf()
return
}
}
if (!isNeeded) {
if (!canStart(this)) {
stopSelf()
return
}
val hasActivityPerm = hasActivityPermission(this)

sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
Expand All @@ -191,7 +194,6 @@ class StepCounterService : Service(), SensorEventListener {
val filter = android.content.IntentFilter().apply {
addAction(Intent.ACTION_BATTERY_CHANGED)
addAction(Intent.ACTION_TIME_TICK)
addAction(Intent.ACTION_CONFIGURATION_CHANGED)
addAction(Intent.ACTION_SCREEN_ON)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ object CalendarFetcher {

while (cursor.moveToNext() && events.size < 10) {
val eventId = cursor.getLong(eventIdIdx)
val title = cursor.getString(titleIdx) ?: "No Title"
val title = cursor.getString(titleIdx) ?: context.getString(R.string.widget_no_title)
val begin = cursor.getLong(beginIdx)
val end = cursor.getLong(endIdx)
val calId = cursor.getLong(calIdIdx)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,6 @@ object WidgetRenderer {
}
val sizeEvents = prefs.getFloat("size_events", 14f)

val bweather = if (showWeatherCondition) {
com.leanbitlab.lwidget.weather.BreezyWeatherFetcher.fetchLocalWeather(context)
} else null
val showWeatherIconOnly = prefs.getBoolean("show_weather_icon_only", false)

val useDynamicColors = prefs.getBoolean("use_dynamic_colors", true)
Expand Down Expand Up @@ -236,6 +233,11 @@ object WidgetRenderer {
return alarmViews
}

// Full render only: partial updates above never touch weather, so skip the JSON parse
val bweather = if (showWeatherCondition) {
com.leanbitlab.lwidget.weather.BreezyWeatherFetcher.fetchLocalWeather(context)
} else null

val views = RemoteViews(context.packageName, layoutId)

// Background & Outline
Expand Down
Loading
Loading