One of the reasons why using the MetaWear sample Android app is a big jump for those new to Android is that it involves multiple activities and especially because it uses fragments which build upon other fragments. This can make some parts of it seem like a black box without some serious digging. In this section, I’ll unpack some of the more basic parts of the sample app. As a result, there will be a slight jump in complexity…But if you’ve made it this far, you’re probably ready.
We are going to add the Sample app’s ScannerActivity.java to our project. This will allow us to select from multiple different boards, and eventually to manage our bluetooth connections more effectively.
To begin, we need to add a new dependency to our app build.grade file:
Be sure to sync the project after adding the new dependency.
Next, create the new activity. In Android Studio, go to File –> New –> Activity –> Blank Activity
Call the activity, ScannerActivity. The associated layout name will automatically update.
We add the ScannerActivity to our AndroidManifest.xml
Note that scanner activity is now the LAUNCHER activity, and that we have removed that action from .MyActivity. If you run your app you should see the ‘Hello World’ message.
Let’s update our activty_scanner.xml layout file. The ScannerActivity will require the ids we update here:
You’ll note (and Android Studio will tell you) that a few strings need adding. Add these to your strings.xml file:
OK, now we’re ready to get to work on the ScannerActivity.
By checking against the branch version-0.8, make sure you’ve got all the imports required (there are quite a few).
We will be implementing both a ServiceConnection and a ScannerCommunicationBus in our activity, so the syntax is as follows:
Both of these have certain required methods. From part 3 You should already be familiar with those required for the ServiceConnection:
And there are a few standard activity setup methods to complete also:
Now we need to implement the methods for ScannerCommunicationBus. First, we’ll need a few variables (including our TAG variable for logging):
And then the methods themselves:
At this point, we have a basic structure. If you run the app, you will see the scanner activity with a scan button, but nothing will happen when you press the button. Let’s add more code:
We now have enough code to search for the boards over bluetooth without manually entering the MAC address. If you run the app and hit “Scan”, then a list of the MetaWear boards within range will be displayed:
The line of code in our log above mwBoard.getMacAddress() also ensures that when you select a board, its MAC address is displayed in the log:
Since this post is already quite long, I’ll break it into two sections. In section II, I will show you the next steps after selecting a board using our new ScannerActivity.
Note You can view all these changes in the github repository on the branch version-0.8