Skip to content

Commit

Permalink
#22 Fix: find activity properly by traversing Context
Browse files Browse the repository at this point in the history
  • Loading branch information
PatilShreyas committed Mar 17, 2022
1 parent 1edf849 commit 90ac11c
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions capturable/src/main/java/dev/shreyaspatil/capturable/Capturable.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ package dev.shreyaspatil.capturable

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Build
Expand Down Expand Up @@ -129,8 +130,7 @@ private suspend fun View.drawToBitmapPostLaidOut(context: Context, config: Bitma
// "Software rendering doesn't support hardware bitmaps"
// See this issue for the reference: https://github.com/PatilShreyas/Capturable/issues/7
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val window = (context as? Activity)?.window
?: error("Can't get window from the Context")
val window = context.findActivity().window

drawBitmapWithPixelCopy(
view = view,
Expand Down Expand Up @@ -180,3 +180,15 @@ private fun drawBitmapWithPixelCopy(
Handler(Looper.getMainLooper())
)
}

/**
* Traverses through this [Context] and finds [Activity] wrapped inside it.
*/
internal fun Context.findActivity(): Activity {
var context = this
while (context is ContextWrapper) {
if (context is Activity) return context
context = context.baseContext
}
throw IllegalStateException("Unable to retrieve Activity from the current context")
}

0 comments on commit 90ac11c

Please sign in to comment.