How to get work with DecorView? .GetContext () in DecorView getting DecorContext

In Android 7, getting the DecorView context returns the DecorContext class, and this is not an Activity. I used to work with Activity a = (Activity)view.getContext() , but it no longer worked for DecorView on Android 7. Is there an effective way to get activity from DecorView?

I use reflection to get the DecorView window, and then get the context of this window (which is Acitivity) at the moment.

 Field f = decorView.getClass().getDeclaredField("mWindow"); f.setAccessible(true); Window w = (Window) f.get(decorView); Activity a = (Activity) w.getContext(); 

Is there a way that uses the standard API?

+6
source share
1 answer

In Android 7 (Nougat), Android introduced a multi-window function that allows you to immediately open 2 actions on the screen (whether it’s your actions or 2 different ones). To do this, they introduced a new class called DecorContext , which will be used by DecorView . DecorContext is a (quote) "Context for decor views that can be visited using the pure context of the application and are not activity-dependent, but still provide some of the features that Activity has, such as themes, resource-based activity, etc. d. ". This means that DecorView no longer knows which Activity it belongs to, only to which Application . Therefore, based on Nougat, it is impossible to get an Activity only from DecorView .

Not sure if it still applies to you, but you can do this:

 Activity a = (Activity) decorView.findViewById(android.R.id.content).getContext(); 
+5
source

All Articles