Static way to get 'Context' in Android?

前端 未结 19 2679
猫巷女王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:28

    I've used this at some point:

    ActivityThread at = ActivityThread.systemMain();
    Context context = at.getSystemContext();
    

    This is a valid context I used at getting system services and worked.

    But, I used it only in framework/base modifications and did not try it in Android applications.

    A warning that you must know: When registering for broadcast receivers with this context, it will not work and you will get:

    java.lang.SecurityException: Given caller package android is not running in process ProcessRecord

    0 讨论(0)
提交回复
热议问题