Access to application class in Broadcast Receiver

前端 未结 2 705
慢半拍i
慢半拍i 2021-01-02 02:01

I want to check internet connection in Broadcast Receiver; And set result (A boolean flag) to a global variable, to use it on whole application, in if conditions; That if in

相关标签:
2条回答
  • 2021-01-02 02:33

    Maybe it will help somebody. If using own application class:

    public class App extends Application {
    
        private static App sInstance;
    
        public static App get() {
            return sInstance;
        }
    
        @Override
        public void onCreate() {
            sInstance = this;
            super.onCreate();
        }
    
    }
    

    Then you can use App.get() in your broadcast receiver. According to onCreate() docs it will be called before receiver calls.

    Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

    0 讨论(0)
  • 2021-01-02 02:49

    You can access your Application class in BroadCastReceiver by using its context,

     @Override
     public void onReceive(final Context context, Intent intent) {
       MyApplication mApplication = ((MyApplication)context.getApplicationContext());
     }
    
    0 讨论(0)
提交回复
热议问题