Skip to content

Commit 6a52988

Browse files
Fix: Add RECEIVER_NOT_EXPORTED flag for BroadcastReceiver registration
Addresses a SecurityException crash on Android 13 (API 33) and higher when programmatically registering a BroadcastReceiver in PhotoReasoningViewModel. The init block in PhotoReasoningViewModel, which registers `aiResultReceiver` to listen for AI call results from ScreenCaptureService, now checks the Android version: - If running on Android 13 (API 33) or above, `Context.RECEIVER_NOT_EXPORTED` flag is included in the `registerReceiver` call. - For older versions, the previous registration method is used. This ensures compliance with Android 13's requirement for specifying receiver export behavior, resolving the crash.
1 parent 22e2738 commit 6a52988

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

app/src/main/kotlin/com/google/ai/sample/feature/multimodal/PhotoReasoningViewModel.kt

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import android.content.Intent
77
import android.content.IntentFilter
88
import android.graphics.drawable.BitmapDrawable
99
import android.net.Uri
10+
import android.os.Build
1011
import android.util.Log
1112
import android.widget.Toast
1213
import androidx.lifecycle.ViewModel
@@ -145,10 +146,22 @@ class PhotoReasoningViewModel(
145146

146147
init {
147148
// ... other init logic if any ...
148-
val filter = IntentFilter(ScreenCaptureService.ACTION_AI_CALL_RESULT)
149-
// Ensure context is available for registration; use applicationContext for broader lifecycle
150-
MainActivity.getInstance()?.applicationContext?.registerReceiver(aiResultReceiver, filter)
151-
Log.d(TAG, "AIResultReceiver registered.")
149+
val context = MainActivity.getInstance()?.applicationContext
150+
if (context != null) {
151+
val filter = IntentFilter(ScreenCaptureService.ACTION_AI_CALL_RESULT)
152+
// Comment: Specify RECEIVER_NOT_EXPORTED for Android 13 (API 33) and above
153+
// to comply with security requirements for programmatically registered receivers.
154+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
155+
context.registerReceiver(aiResultReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
156+
} else {
157+
context.registerReceiver(aiResultReceiver, filter)
158+
}
159+
Log.d(TAG, "AIResultReceiver registered.")
160+
} else {
161+
Log.e(TAG, "Failed to register AIResultReceiver: applicationContext is null at init.")
162+
// Consider if this state implies a critical failure for the ViewModel's operation.
163+
// For now, just logging.
164+
}
152165
}
153166

154167
override fun onCleared() {

0 commit comments

Comments
 (0)