Android Wear OS Recent Apps

Recently I went for a bike ride and decided to record my ride using my Pixel Watch (Running Wear OS). I wanted to record my data both on Strava and Fitbit. What I realized about midway through my ride is only one of these apps can record at a given time.

First I started Fibit recording and then started Strava recording. Midway through the ride I wanted to compare the data between the two apps. I used the Pixel Watch side button to access the recent apps. When switching back to Fitbit I realized it wasn’t recording so I started it again, but quickly realized Strava quick recording. This is much different than running two apps on an Android phone. Most likely a limitation added to Wear OS to ensure device longevity.

What I quickly realized are a few things when using the Pixel Watch Wear OS device.

  • Ensure your phone Fitness app has a Wear OS app. I say this because its much much easier to start, monitor, pause, or stop a workout from your wrist. User with a Wear OS device will more than likely use an app that has the watch app too.
  • You cannot run two apps (Fitbit & Strava) on the Pixel Watch. You need to choose one and hope it shares data to other fitness apps you enjoy / use.
  • After stopping the Strava workout I noticed that Fitbit asked to sync data. I believe what happened here is Strava wrote my workout data to the new Wear OS 3 Health Service. This is completely awesome as it allows apps to share, and received, data. But more importantly users can decide if they want to share the data and to which apps.
  • Using the Strava Wear OS app I noticed UI/UX is super important. I thought I had a notification, which is a small white dot at the bottom or the screen, but it was just the page indicator indicating the app had multiple pages to swipe. The difference between how Fitbit designed the page indicators versus Strava is critical in my opinions. On Fitbit it’s very obvious there are 3 pages to swipe through, but on Strava I could see the other dot(s) and though it was a one page app.

This is a small post, but thought it was important to share. More and more people will start using fitness watches and it will be critical for fitness apps to extend to the wrist to keep users using their apps. It will also be important to share the fitness data to other services like Wear OS Health Service and potentially other apps like Strava. I use Strava here as it seems like it’s the social media app of fitness and why should users have to run two apps to share their data. I hope you enjoyed the post and continue using Android powered fitness apps.

LinkedIn: Matt Graham
Twitter: @bline163

Jetpack Compose – Where’s Gravity

Have you starting playing with Android Jetpack Compose and run into the situation where you can not figure out how to center align a text view properly. Well you’re in luck because I’ve been messing around with Compose recently and figured it out.

First I’m going to start with the situation where creating a text composable within a parent composable isn’t aligning correctly. Below is an image of the preview and the source code to create this situation.

Here is the source for the above image:

@Composable
fun BoxWithTextView(greeting: String) {
    Box(
        modifier = Modifier
            .size(275.dp)
            .background(Color.Red)
    ) {
        Text(text = greeting)
    }
}

Pretty basic, but I want the text aligned in the center. I looked at the Text() composable and notice there is a textAlign parameter so figured I’d set that and align my text. After setting textAlign = TextAlign.Center and building the code, nothing changed. See the image below as nothing changed.

I quickly realized the Text composable wasn’t the full width of the view. I then added the following changes:

@Composable
fun BoxWithTextView(greeting: String) {
    Box(
        modifier = Modifier
            .size(275.dp)
            .background(Color.Red)
    ) {
        Text(text = greeting,
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Yellow),
            textAlign = TextAlign.Center)
    }
}

With the above changes all that happened is my Text composable filled up my parent Box composable. Still not what I wanted, which was placing the text in the middle of the parent view. I then added a style within the Text composable itself and still no luck with centering the text. Below is what I added within the Text composable parameters:

style = TextStyle(
textAlign = TextAlign.Center
),

Finally after playing around a bit with all of these composables I came across contentAlignment parameter of the parent Box composable. With this parameter you have the ability to specify all sorts of different alignments. The one I was looking for was Center. Also note I had to remove the Text composable modifier .fillMaxSize() to achieve the design. Here is a pic of the final Box with text centered inside of it.

Here is the final code for the Composable to create this:

@Composable
fun BoxWithTextView(greeting: String) {
Box(
modifier = Modifier
.size(275.dp)
.background(Color.Red),
contentAlignment = Alignment.Center
) {
Text(text = greeting)
}
}

In the end there’s no Gravity anymore! It was fairly basic, the parent Composable is responsible for defining how to align it’s content. I hope this helps save others times when they start playing around with Jetpack Compose.

LinkedIn: Matt Graham
Twitter: @bline163
Github: https://github.com/mattgraham1

Google Fit Two Week Daily Step Count

This blog post is about the Google Fit API for Android (https://developers.google.com/fit/android), to write a quick app that can show your cumulative step counts for the last two weeks. I hope my learnings will help others.

The overall design of this application is fairly basic, create a view that will display a table with rows that show two columns (date and step count). Initially show the rows in descending order with the current date as the first row. The add a button in the toolbar to show the results in descending or ascending order.

One of the biggest take aways I learned from this was the data is returned in buckets (https://developers.google.com/android/reference/com/google/android/gms/fitness/data/Bucket) and you don’t just get the step count data directly from a quick API call. Next these buckets contain datasets (https://developers.google.com/android/reference/com/google/android/gms/fitness/data/DataSet), which then contain data points (https://developers.google.com/android/reference/com/google/android/gms/fitness/data/DataPoint), and eventually a list of Fields (https://developers.google.com/android/reference/com/google/android/gms/fitness/data/Field). From here you can get the step counts and accumulate the results. There is a method readDailyTotal() but that is only for the current dates total step count. This doesn’t account for previous dates. Therefore I had to crate a read request and call the readData(readRequest) method.

One thing I goofed up on was not setting the date time correctly. To ensure you’re getting a days full step count you need to start at 00:00:00, which at first I was just getting the current time and my results were not matching the Google Fit apps daily step counts. One I update the start times to 00:00:00 I was getting accurate step counts.

The other learning lesson was I needed to create a proper DataSource and pass that to the DataReadRequest. Without doing this my daily total steps weren’t correct when compared to Google Fit app.

In the end this was a fun project to learn more about GoogleFit API. I hope others can learn from this too. Enjoy! Please add, of find, me via the following:

LinkedIn: Matt Graham
Twitter: @bline163
Github: https://github.com/mattgraham1/MyStepCounts

Android Jetpack Compse

Android’s Jetpack Compose is their new modern UI toolkit to build native UIs. As of this writing Jetpack Compose is still in developer preview and they advise to not use it in production application. In this blog post I’ll document how you can quick build easily useable UI components and how you can implement screen navigations.

The goal of this app was to build a simple UI with a list that contains text and cards. When a user clicks on one of the cards it’ll navigate to another UI screen. It builds the basics of a very simple app. NOTE: as this time you need to use AndroidStudio 4.0, I was on the canary channel using v8. You can find the source code on my github repo here: https://github.com/mattgraham1/JetpackComposeExample

In the MainActivity class and within the onCreate() callback there’s a call to setContent{}. This is where all the UI magic happens. If you following the method calls you can see it calls smaller methods that have the “@composable” annotation. This annotation indicates that the it’s a composable UI function. These functions can be chained together to build up your applications UI.

VerticalScroller() {
            Column() {
                Card()
                Text("Hello $name!", Spacing(left = 16.dp, right = 16.dp))
                Text("Text1", Spacing(left = 16.dp, right = 16.dp))
                Row(modifier = Spacing(left = 16.dp, right = 16.dp)) {
                    Text("Row1")
                    Text("Row2")
                }
                Card()
                Card()
            }
        }

As you can see from the code snippet above you can combine multiple different composable functions together into one composable function. This allows your UI code to be broken down into specific functions, and then build up in another function. Code can easily be reused too. Honestly, I really find this pattern very nice and intuitive when building out a UI.

The next thing I will cover is navigating to another UI screen using Jetpack Compose. Currently this toolkit is still in early development stages and navigation haven’t been implemented fully. But they do have a method called “Crossfade” that allows to switch between two layouts with a crossfade animation. All we really have to do here is just switch to another composable functions.

@Composable
private fun AppContent() {
    Crossfade(ScreenStatus.currentScreen) { screen ->
        Surface(color = (+MaterialTheme.colors()).background) {
            when (screen) {
                is Screen.Home -> Greeting(name = "Android")
                is Screen.Details -> CardDetails()
            }
        }
    }
}

sealed class Screen {
    object Home : Screen()
    object Details : Screen()
}

@Model
object ScreenStatus {
    var currentScreen: Screen = Screen.Home
}

/**
 * Temporary solution pending navigation support.
 */
fun navigateTo(destination: Screen) {
    ScreenStatus.currentScreen = destination
}

The code above was basically copied from the Jetpack Compose “Jetnews” tutorial app. That tutorial really doesn’t explain what’s happening. To understand how all this works is the ‘Crossfade’ methods first parameter is a key representing your current layouts state. For my app this is ‘Screenstatus.currentScreen’. Then this state changes when the ‘navigateTo()’ function is called. Once the state changes it automatically calls the ‘Crossfade()’ function again and that is where it will point the layout to a specific composable function. Pretty neat how they implemented this, but as this toolkit matures I’m thinking it’ll be much easily when some sort of navigation component.

Well that’s all I have for this short blog on Jetpack Composable. I know it was a very basic app, but I just wanted to understand the fundamentals and help share what I learned. I hope others enjoy this and can learn from it too.

Please find me or add me via the following:

LinkedIn: Matt Graham
Twitter: @bline163
Github: https://github.com/mattgraham1/JetpackComposeExample

Update: Here’s a great podcast from the Android team about Jetpack Compose:
http://androidbackstage.blogspot.com/2020/01/episode-131-jetpack-compose-and.html

Android Jetpack Component – CameraX

Android Jetpack Component CameraX was built to help make camera app development easier. This blog is how I used the CameraX component to build the FaceTracker app. Here is a link to the CameraX documentation https://developer.android.com/training/camerax

The main idea behind this app was to capture the mobile device’s front facing camera image feed, track a users face, and put some cartoon looking eyeballs on the screen to follow the face being tracked.

Couple of the components used in the project are Android Jetpack CameraX and Firebase Machine Learning Vision. CameraX was used to capture the mobile device front facing camera feed and the Firebase ML vision was used to detect faces within the camera feed. This was all done by creating a ImageAnalysisConfig() and then an ImageAnalysis use case. The image analysis use case was then bound to the CameraX lifecycle.

Within the code the image analysis method gets a ImageProxy, from there you can get the camera image. Next, I created a Firebase vision face detector and passed the image to it to detect faces. When a face is detected I then find a face landmark and pass that to a custom View class I named Eyeball. The Eyeball class overrides the onDraw() method to generate the two eyeballs. This is accomplished by drawing directly to the canvas by drawing an oval and then a circle inside the oval.

Here’s a screen grab of the app with a camera preview to see it tracking me moving about the room.

This project has been fun to learn more about CameraX, Firebase ML Vision, and writing a custom View to draw onto the canvas. I hope everyone enjoys this and can learn from it too. Please find the code and all my info linked below. Enjoy!

LinkedIn: Matt Graham
Twitter: @bline163
Github: https://github.com/mattgraham1/FaceTracker

Flutter Events Calendar

This is my blog post about the Flutter “Events Calendar” project I crated to help myself better understand developing a mobile project in Flutter.

I started this project months ago, but am now just getting around to writing a blog about it. The idea came from my lack of remembering all the various events (Holidays, Birthdays, Parties, Etc.) that happen in my life. Yes, I know you can achieve this with Google calendar or what ever calendar systems your mobile device has by default, but I wanted to take a dive into writing an app using flutter. It has been a fun adventure and I hope you’ll learn or enjoy what I have to share.

You can find the code and more documentation at my public github site here: https://github.com/mattgraham1/FlutterCalendar

Overall this project consists of an Android and iOS application, backend Firestore database, cron job scheduler, and finally sending pushes to the mobile application. Please note I’ve been developing Android apps for years now and much more versed with Android. I know enough about iOS to get by.

Flutter:

First I’ll discuss my experience with using Flutter as the main mobile development tool. Note, I’ve mainly been writing Android apps using the typical xml layout and java code. Writing an app using Flutter was a pleasant experience. All code is writing dynamically and is much much faster to iterate to the device / simulator. As you all probably know AndoridStudio is a great tool to use and continues to shine with Flutter installed too. One area I struggled with early on is just know which widgets to use and how to combine then to build the UI layout I wanted. Ultimately digging into Flutters documentation and Googling a bit you can find plenty of other examples to help you learn. This was also nice and kept me active in continuing this project. One are I’d like to improve more on is implementing better UI building patterns so my main build() method wouldn’t get so large. Honestly I think this is just due to this being my first Flutter app. In the future I plan to try and iterate on this and improve the code. Maybe a future blog post. 🙂

Firebase:

The other major part of this app was the backend, which needed to handling saving all the calendar events and contacts. Again, I used another tool I wasn’t familiar with Firebase Firestore. Here I needed to understand how to sync a users data to Firestore. This tool uses a collection / document type structure and I used the users email address to sync between different main collections (i.e. CalendarEvents and Users). There’s probably a much better way than this, but it worked for me and is still working today.

To glue all of this functionality together I also had to implement Firebase Functions to due two things: push notification and deletion of users contacts. Again, this is something I’ve never done in the past and it uses Node.js. In a high level overview I have a cron job that runs once a day and calls one of the Firebase Functions to query the Firestore database and find any calendar events in the next 24 hours. The once it finds I then get the users push token and send a push notification to their mobile device. This helps the user know when they have a calendar event coming up. The delete function is just that, a way for me to delete users contact(s) entries in the Firestore databases as at the time there was no easy way of deleting sub-collections with the Firestore SDK.

Conclusion:

There you have it, one of my first blogs and my first Flutter / Firebase project I’ve ever created. It was a great learning experience for me and I hope sharing this will help others have the same experience. Remember you can see the project on my github account here: https://github.com/mattgraham1/FlutterCalendar

Create your own website, free on WordPress.com.Create your own website.
Start free