I recently set out to see what all the hype was about and built my first React
Native app: openHIIT, a timer for
Tabata-style interval training. It won't be available on the Play Store, but you can
download the apk on GitHub. In
my experience, React Native is far from a complete solution for abstracting
away the underlying OS. Unlike my experiences with
Ionic, I found myself digging into the Java
code regularly with React Native. Right now, there is no way to do basic tasks
like playing audio,
KEEP_SCREEN_ON flag, or even setting the app's name and
icon, without diving into React Native's underlying Java code.
In this post, I'll quickly describe how to make sure Android never puts the phone to sleep while your app is running. This may seem like a simple task, but there's plenty of questions about this topic and corresponding bad advice on StackOverflow. I quickly realized during my first workout that this feature was necessary for the app, but ended up spending hours figuring out how to get this to work. Hopefully this quick post will save you some time.
React Native Android Project Layout
TLDR; diff on GitHub
Below is the basic layout of the Android project for openHIIT with React Native 0.19.0.
A lot of this code is just build logic automatically generated by React Native
that you never have to touch. However, in my experience, just about every app
will have to make modifications to the
For instance, any fonts that you want to use in your app need to be included
as ttf files in
The most important file, however, is the
MainActivity.java file highlighted
above. In Android, an activity is the code organizational unit immediately
underneath an app - all Android code starts in an activity. If you're not
familiar with Android development, you can think of an activity as being
roughly analogous to a component in React. By default, React Native projects
have only one activity, whose responsibility is rendering whatever the output
of your React components is. In order to keep Android awake while your app
is up, you're going to modify
Android activities have lifecycle hooks much like React components. Since
MainActivity needs to run before any React Native components get rendered,
onCreate() method is
the right place to tell Android to keep your app awake. So all you need to
do is import a couple files and override the
onCreate() method for your
MainActivity to set the
KEEP_SCREEN_ON flag correctly.
React Native is powerful, but in order to use it in any meaningful way on Android, you need to be willing to get your hands dirty and dig into the Java. Some surprisingly basic tasks can't be done through JS, including forcing the screen to stay on. Writing React Native code is a lot easier than building a native android app from scratch, but you still need to be familiar with the basics of native android development before setting out to build a React Native app.