Gain Access to ReactContext or ReactApplicationContext in MainActivity
Hello
How to gain access to ReactContext or ReactApplicationContext in Main Activity? The primary use case is: When a phone call occurs, I would want to do certain things inside my app. But in order to communicate from the Native side to JS side, I thought of emitting events. In order to emit events, I need access to ReactContext or ReactApplicationContext.
I tried using ReactInstanceManager.getCurrentReactContext in onCreate(). But it returns null. Is there some simple solution for such use cases?
Right now, The code is as follows:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mReactRootView = new ReactRootView(this); mReactInstanceManager = ReactInstanceManager.builder() .setApplication(getApplication()) .setBundleAssetName("index.android.bundle") .setJSMainModuleName("index.android") .addPackage(new MainReactPackage()) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED) .build(); mReactRootView.startReactApplication(mReactInstanceManager, "swipezen", null); phoneStateListener = new MyPhoneStateListener(mReactInstanceManager.getCurrentReactContext()); TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); setContentView(mReactRootView); }
Thanks in Advance Lalith
Why not make it a module, which can simply access to ReactApplicationContext?
@mjhlybmwq I think a good reason is you can trigger the onPause/onResume events here.
@facebook-github-bot stack-overflow
Hey @lalith26 and thanks for posting this! @christopherdro tells me this issue looks like a question that would be best asked on StackOverflow. StackOverflow is amazing for Q&A: it has a reputation system, voting, the ability to mark a question as answered. Because of the reputation system it is likely the community will see and answer your question there. This also helps us use the GitHub bug tracker for bugs only. Will close this as this is really a question that should be asked on SO.
@raymanyoung Just a reminder that we can use the LifecycleEventListener interface to access onPause / onResume. I'm not sure if that was available when you posted your comment, though.
@sampurcell93 Yeah, when I posted that comment the AppState was not available on Android (or I just did not update RN version to latest at that time). And now I have already found what I should do to make it work.
Thanks a lot! =)