Static way to get 'Context' in Android?

前端 未结 19 2735
猫巷女王i
猫巷女王i 2020-11-21 06:36

Is there a way to get the current Context instance inside a static method?

I\'m looking for that way because I hate saving the \'Context\' instance eac

19条回答
  •  遥遥无期
    2020-11-21 07:01

    Here is an undocumented way to get an Application (which is a Context) from anywhere in the UI thread. It relies on the hidden static method ActivityThread.currentApplication(). It should work at least on Android 4.x.

    try {
        final Class activityThreadClass =
                Class.forName("android.app.ActivityThread");
        final Method method = activityThreadClass.getMethod("currentApplication");
        return (Application) method.invoke(null, (Object[]) null);
    } catch (final ClassNotFoundException e) {
        // handle exception
    } catch (final NoSuchMethodException e) {
        // handle exception
    } catch (final IllegalArgumentException e) {
        // handle exception
    } catch (final IllegalAccessException e) {
        // handle exception
    } catch (final InvocationTargetException e) {
        // handle exception
    }
    

    Note that it is possible for this method to return null, e.g. when you call the method outside of the UI thread, or the application is not bound to the thread.

    It is still better to use @RohitGhatol's solution if you can change the Application code.

提交回复
热议问题