I have an Android app which needs to run an overlay activity with some content in it over other apps on the phone at the moment they start or get focused. For this, I use AccessiblityService
:
override fun onAccessibilityEvent(event: AccessibilityEvent) {
if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (cond1) {
// (!)
// this will get triggered properly
//
val intent = Intent(this, MyOverlayActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
}
}
However, it'll only get launched properly whenever I switch to my own activity - MainActivity
.
What's the matter?
MyOverlayActivity:
class MyOverlayActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 1
// window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
// val layoutParams = WindowManager.LayoutParams(
// WindowManager.LayoutParams.MATCH_PARENT,
// WindowManager.LayoutParams.MATCH_PARENT,
// WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
// PixelFormat.TRANSLUCENT
// )
// window.attributes = layoutParams
//
// 2
window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
)
window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
window.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT
)
window.setGravity(Gravity.BOTTOM)
//
setContentView(R.layout.activity_my_overlay_layout)
}
}
Manifest
<!-- [.............] -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<!-- [.............] -->
<activity android:name=".MyOverlayActivity"
android:exported="true"
android:theme="@style/AppTheme.TranslucentNoTitleBarFullscreen"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|navigation">
</activity>
Note I've given the permission required to my app in Acessibility.