Archives for android

MQTT Android Studio App

 

Creating a native MQTT App provides a convenient platform for complete customization of any IoT project. Yet the effort to develop a Android Studio App can seem daunting. With a huge learning curve just to accomplish the simplest of tasks.

To my surprise, however, I found it reasonably simple and easy to create a basic app framework upon which to expand into a full-blown tool for MQTT interactions.


For those that just cannot wait, here is the project. You can even install the apk file app-debug.apk on your Android device now.


Keeping things reasonably simple and easy, here is how I did it…

Installing Android Studio

This was as easy as a google search and file download. Use this link to install Android Studio on a PC with Windows 10 operating system.

Install Android Studio

Creating the Project

After installing and opening Android Studio, create a new project (File->New->New Project…

Enter a name for the project and click “Next”. The project location can be anywhere on your hard drive, ending with the folder name matching the project name:

These were the default settings used on the next screen:

Next, Select “Bottom Navigation Activity”.

Use the default activity name:

Click “Finish” to complete the App framework creation.

The demo App will build.

Before we add the code for MQTT, it would be a good idea to build the apk and install the app on your android device to make sure the framework is functional.

Select Build-> Build APK(s) from the menu.

 

Click on “locate” to open the file manager with the location of the apk. You can transfer this file to your android device to test the app framework. The app should start to the following screen:

Now lets add the MQTT Demo code.

For this exercise, close Android Studio and simply replace the contents of the project folders with the files I have uploaded to Github here. Then we will walk through the code.

Copy <github/MQTTDemo> folder to <your project base directory>/MQTTDemo

The project files is partitioned into 3 main folders:

  1. <your project base directory>/MQTTDemo/app/build
  2. <your project base directory>/MQTTDemo/app/libs
  3. <your project base directory>/MQTTDemo/app/src

The build folder contains the output files from the build, libs contains the paho MQTT libraries, and src has the source code for the project. You can download the paho library files from here.

Now let’s open Android Studio to this project and review the source code:

The MQTT libraries as dependencies of your Android project

Open the build.gradle file. Here you will see the paho libraries added to file dependencies section:
dependencies {
    …    
    compile files(‘libs/org.eclipse.paho.android.service-1.1.1.jar’)
    compile files(‘libs/org.eclipse.paho.client.mqttv3-1.1.1.jar’)
}

Permissions and Service additions to the AndroidManifest.xml file

Open the app/AndroidManifest.xml file. Note the following permissions required by the app added to the manifest:
<usespermission android:name=“android.permission.INTERNET” />
<usespermission android:name=“android.permission.WAKE_LOCK” />
<usespermission android:name=“android.permission.ACCESS_NETWORK_STATE” />
<usespermission android:name=“android.permission.READ_PHONE_STATE” />
The Paho Android Service must also be added within the manifest <application> tag.

Customizing the App GUI (activity_main.xml file):

From Android Studio, the app opening GUI is layout is defined in the file app/res/layout/activity_main.xml

A preview of the GUI can be seen by selecting the “Design” tab while the xml code needed to generate the GUI can be edited from the “Text” tab.

While not necessary, inn order to make it easy to follow, the GUI components are listed in the xml file in the top-to-bottom order that they appear on the screen.

  • LinearLayout…requestFocus

Note that this object has a defined width and height of 0px, making it invisible. This object is used to set initial focus when the App is opened. Without this object, the app sets focus on the first editable field and the edit alphabet pop-up appears, somethings that is clearly undesirable on start-up.

  • LinearLayout…ScrollView…TextView

This object is the large white space in the layout above. It displays MQTT messages as they are received.

  • TableLayout

This object is the tabular information on the bottom half of the screen. This table is used to input MQTT connect parameters and to display the connect status.

  • BottomNavigationView

This object is the icons and text along the bottom of the screen. Upon tapping, these items trigger action by the app.

Bottom Navigation Menu (app/res/menu/navigation.xml file)

This file defines the five navigation items displayed along the bottom row of the screen. Three fields are needed for each item.

  1. id – identifies the item for access in the java code
  2. drawable = defines the item icon
  3. title – defines the text to be displayed under the item icon

The icons can be selected from the Android Studio library or a custom icon can be used. To add an icon to the project, right click on the app->res->drawable folder selecting New->Drawable resource file:

The java code (app/java/<project package name>/MainActivity.java)

The startup and callback code is contained in the MainActivity.java file. A separate file is needed for each app scree. Since this demo app only uses 1 screen, only 1 file is needed.

The App code (class Methods) are contained within the MainActivity class.

This apps simple method simple structure:

  1. onCreate – Executed upon App start-up
  2. <strong>RunScheduledTasks</strong> - Runs scheduled tasks once every second
  3. <strong>OnNavigationItemSelectedListener</strong> - Callback executed when a bottom navigation item is tapped.
  4. <strong>mqttCallback</strong> - Callback executed whenever a subscribed MQTT message is received

How it Works

When the app is started, GUI is rendered and onCreate is executed. Here is the sequence performed in onCreate:

  1. GUI layout is associated with the Apps opening activity
  2. A custom icon is added to the app’s title bar (you can change this, of course)
  3. A vertical scroller is added to the message window
  4. A client connection to the MQTT broker defined by the GUI table is made
  5. The bottom Navigation menu callback is registered.
  6. The text under each Navigation icon is made visible
  7. The callback for MQTT messages is registered
  8. The 1 second scheduled tasks callback is registered

After startup, the 3 app callback are active, waiting for a trigger to initiate execution

1. Scheduled tasks (runs once per second)

This App only requires one scheduled task. The app checks to see if the MQTT client is still connected to the broker. If connected, the display says “Connected” in green text. If the connection is lost, it displays “Disconnected” in red text.

2. Navigation Callback

The callback determines which item was tapped and then performs the applicable action:

Button 1: Connect – If connected to the broker, the connection is closed and then reconnected using the parameters currently displayed in the table. You can change the broker url prior to tapping this button to connect to a different broker, The table also has field for username/password if the broker supports and requires those fields. Using the paho library, two connection types are supported: tcp and ssl. An example of the broker url format for these connections:

tcp://&lt;broker domain&gt;:1883
ssl://&lt;broker domain&gt;:8883

Button 2: Subscribe – If connected to the broker, a subscription to the topic entered in the table is made. But if not connected, a message is displayed indicating a subscription cannot be added unless connected to the broker.

Button 3: Publish – If connected to the broker, the message entered is published to the topic entered in the table. But if not connected, a message is displayed indicating a message cannot be published unless connected to the broker.

Button 4: Clear – Erases the content of the message window.

Button 5: Exit – Exits the App.

3. Subscribed Topic Callback

The code executed when a subscribed message is receive is structured as if/then conditional statements. Once condition is executed for each unique topic executed. This provides a mechanism to execute topic specific code.

But in this demo App, the specified unique topics are not used. In that condition, the default “else” case is executed, which simply echos the published message in the message window.

In Closing

With the App framework presented, a full-featured app can be developed to interface with an MQTT broker to monitor and control your IoT devices. It can also be used as a client to test out MQTT clients connected to a common broker. Once again, the project can be downloaded from Github here.

Hope you find this project useful.

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr

Native Android App Development Using Only HTML-Javascript-CSS

cordovaHere’s a handy gem for your bag of tricks. Did you know that a native Android App can be developed using only the web familiar html, javascript and css? Without the need to dig deep into the bowels of the OS.

Yep, it is definitely possible – all while still offering control of all your device’s interfaces such as cameras, bluetooth, wifi…you name it. You see, the hardware dependent components are supported with an Apache developed framework called Cordova. And while this article focuses on the Android platform, the same App can easily be ported to ios or Amazon Fire, with little or no change. Making it possible to develop your App once for distribution across several different device types.

Here is how to setup the development environment and install an application on an Android device.


Setting Up The Environment

The trick is using Cordova to provide a platform for building native applications using only HTML. CSS, and Javascript.

What is Cordova?

This is a group of  APIs supporting the development of native Apps without using the language of the device. These APIs provide access to the device’s hardware sensors. And with a few simple steps, you are up and running, developing your unique application.

Step 1:

Install node.js from nodejs.org

This will allow you to run “node” and “npm” from a command line window.

Step 2:

Install a git client from http://git-scm.com/.

This will allow you to invoke “git” from a command line.

Step 3:

Install the Cordova module using npm by entering the following at the command line:

npm install -g cordova

Step 4:

Setup the Eclipse for Android App Development Environment by following the following instructable:

http://www.instructables.com/id/How-To-Setup-Eclipse-for-Android-App-Development/?ALLSTEPS


Creating A New Application

Step 1:

Open a cmd windows.

Step 2:

Change directory to the base directory for your workspaces (your choice).

Cd c:\myworkspace

Step 3:

Create new folder with app name (no spaces):

mkdir mynewapp

cd mynewapp

Step 4:

Create app file structure:

cordova create appfiles com.author.mynewapp MyAppTitle

Where

  • “appfiles” is the folder to create the app file structure
  • “com” is the convention used to start the app filename
  • “author” is the developer or company name or initials
  • “mynewapp” is the bame of the app
  • “MyAppTitle” is the title of the app

Step 5:

Add platform (android or ios)

cd appfiles

cordova platform add android

Step 6:

Add plugins as needed (basic required plugins;device,console,file shown here)

Get plugin names from plugins.cordova.io/#/ Then enter the following for each plugin to be added:

cordova plugins add org.apache.cordova.device

cordova plugins add org.apache.cordova.console

cordova plugins add org.apache.cordova.file

In the future, plugins will be delivered using npm. See the instruction at plugins.cordova.io/#/ for more information regarding npm plugin delivery.


Building the Application

Step 1:

Open Eclipse

Step 2:

Install your USB cable from the PC running eclipse to the Android device.

Step 3:

Select Import from the File menu.

Step 4:

Select the base folder created for the newly created project.

Step 5:

First Select “Clean” from the Project Menu.

Step 6:

Then Click on the “Run” icon to build and launch the new app on your device


Editing The Application

The App starts with the launching of the index.html file located at:

<your base app workspace folder>\iotmobile\appfiles\platforms\android\assets\www

this file should be edited to change the functionality of the App. Javascript/Jquery and css files can similarly be customized. They are located at:

<your base app workspace folder>\iotmobile\appfiles\platforms\android\assets\www\js


Conclusion

There you have it!

A quick reference to setting up the Android Development Environment, creating a blank project, building the App and finally loading running it on your device. Now it’s your turn. What will you create?

I hope you find this information useful…

droid

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr