Access to application class in Broadcast Receiver

我是研究僧i 提交于 2019-11-30 13:18:26

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());
 }

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!