Skip to content
Open
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
6 changes: 6 additions & 0 deletions .idea/copilot.data.migration.agent.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/copilot.data.migration.ask2agent.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/markdown.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.androidx.work.runtime.ktx)

// Unit testing dependencies
testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")
Expand Down
13 changes: 10 additions & 3 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
<!-- Foreground services (microphone type required on Android 14+) -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<!-- Used when API 34+ blocks mic FGS until a visible window (MainActivity) exists -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SHORT_SERVICE" />

<application
android:name="io.github.miclock.MicLockApplication"
Expand Down Expand Up @@ -41,16 +43,21 @@
<service
android:name="io.github.miclock.service.MicLockService"
android:exported="false"
android:foregroundServiceType="microphone" />
android:foregroundServiceType="microphone|shortService" />

<receiver
android:name="io.github.miclock.receiver.BootCompletedReceiver"
android:enabled="true"
android:exported="true"
android:directBootAware="true">
<!-- LOCKED_BOOT_COMPLETED is intentionally omitted: CE storage / prefs may be unavailable. -->
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED"/>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_UNLOCKED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>

Comment on lines +60 to 63

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The MY_PACKAGE_REPLACED intent-filter includes <data android:scheme="package" />, which narrows matching to only intents that include data. Intent.ACTION_MY_PACKAGE_REPLACED broadcasts are commonly sent without data; if so, this receiver will never fire on updates. Consider removing the <data> constraint (or verify the broadcast always includes matching data on your supported API levels).

Suggested change
<data android:scheme="package" />
</intent-filter>
</receiver>
</intent-filter>
</receiver>

Copilot uses AI. Check for mistakes.
Expand Down
129 changes: 87 additions & 42 deletions app/src/main/java/io/github/miclock/receiver/BootCompletedReceiver.kt
Original file line number Diff line number Diff line change
@@ -1,74 +1,119 @@
// app/src/main/java/com/example/miclock/BootCompletedReceiver.kt
package io.github.miclock.receiver

import android.Manifest
import android.app.NotificationManager
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.SystemClock
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import io.github.miclock.worker.BootServiceWorker
import java.util.concurrent.TimeUnit
import io.github.miclock.service.MicLockService

/**
* Receives BOOT_COMPLETED broadcast and schedules a WorkManager task to start the service.
* This approach is required for Android 15+ to avoid ForegroundServiceStartNotAllowedException
* when starting foreground services directly from BOOT_COMPLETED.
* After boot / unlock / package replaced, schedules **MicLockService** via
* [PendingIntent.getForegroundService] + [AlarmManager]. Unlike [Context.startForegroundService]
* from app code or [android.app.Activity] launched from a worker, alarm delivery is a
* **system-sent PendingIntent** — not blocked by goo.gle/android-bal the way `BootResumeActivity` was.
*
* Delay lets CE storage and audio stack settle after reboot.
*/
class BootCompletedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_BOOT_COMPLETED || intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) {
Log.d(TAG, "Received ${intent.action}")
val action = intent.action ?: return
val shouldSchedule =
when (action) {
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_USER_UNLOCKED,
Intent.ACTION_MY_PACKAGE_REPLACED -> true
else -> false
}
if (!shouldSchedule) {
Log.d(TAG, "Ignoring action: $action")
return
}

val micGranted = ContextCompat.checkSelfPermission(
context,
Manifest.permission.RECORD_AUDIO,
) == PackageManager.PERMISSION_GRANTED
Log.d(TAG, "Received $action")

// Check notification status but don't require it
val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notifsGranted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // API 33+
nm.areNotificationsEnabled() && ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS,
) == PackageManager.PERMISSION_GRANTED
} else {
nm.areNotificationsEnabled()
}
val appCtx = context.applicationContext
val micGranted =
ContextCompat.checkSelfPermission(appCtx, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED

if (!notifsGranted) {
Log.w(TAG, "Notifications not enabled - service will run without notification updates")
}
if (!micGranted) {
Log.d(
TAG,
"Microphone permission not granted. MicLockService will not start automatically.",
)
return
}

// Only require microphone permission
if (micGranted) {
Log.d(TAG, "Microphone permission granted, scheduling service start via WorkManager")
scheduleAlarmMicStart(appCtx)
}

// Use WorkManager to start the service with a delay
// This avoids Android 15+ restrictions on starting foreground services from BOOT_COMPLETED
val workRequest = OneTimeWorkRequestBuilder<BootServiceWorker>()
.setInitialDelay(5, TimeUnit.SECONDS)
.build()
private fun scheduleAlarmMicStart(appCtx: Context) {
val svcIntent =
Intent(appCtx, MicLockService::class.java).apply {
action = MicLockService.ACTION_START_USER_INITIATED
}

WorkManager.getInstance(context)
.enqueue(workRequest)
val piFlags =
PendingIntent.FLAG_UPDATE_CURRENT or
(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_IMMUTABLE
} else {
0
})

Log.d(TAG, "WorkManager task scheduled to start MicLockService")
val pi: PendingIntent =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PendingIntent.getForegroundService(
appCtx,
ALARM_REQUEST_CODE,
svcIntent,
piFlags,
)
} else {
Log.d(
TAG,
"Microphone permission not granted. MicLockService will not start automatically.",
PendingIntent.getService(appCtx, ALARM_REQUEST_CODE, svcIntent, piFlags)
}

val am = appCtx.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val triggerElapsed = SystemClock.elapsedRealtime() + DELAY_MILLIS

try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setAndAllowWhileIdle(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerElapsed,
pi,
)
} else {
@Suppress("DEPRECATION")
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerElapsed, pi)
}
Log.d(TAG, "Scheduled mic FGS via alarm + getForegroundService in ${DELAY_MILLIS}ms")
} catch (e: Exception) {
Log.e(TAG, "Alarm schedule failed; trying direct startForegroundService", e)
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(appCtx, svcIntent)
} else {
appCtx.startService(svcIntent)
}
} catch (e2: Exception) {
Log.e(TAG, "Direct startForegroundService also failed", e2)
}
}
}

companion object {
private const val TAG = "BootCompletedReceiver"
private const val ALARM_REQUEST_CODE = 0x4D434C42 // 'MCB'

/** Elapsed realtime delay so boot / unlock / audio stack are ready. */
private const val DELAY_MILLIS = 15_000L
}
}
Loading
Loading