Android design support library: TextInputLayout - floating label

By With No comments:

Android design support library introduces a new component called TextInputLayout to handle EditText and form.

Topics covered

Android material design

Android design support library

TextInputLayout with EditText

Android design support library introduced some important new widget that help developer to create consistent UI following material design guidelines.
One of the new component shipped by Android design support library is TextInputLayout that is used to animate EditText labels. To do the job, TextInputLayout uses an EditText attribute, called hint.To show how to use TextInputLayout and EditText, we will create an android app like the one shown below:

Using TextInputLayout, and wrapping EditText inside TextInputLayout, it is possible to control this hint so that it disappears as soon as the user starts writing the text and "moves" to the label position:

Another important feature is the error handling. With TextInputLayout it is possible to show error messages near to the EditText.

How to use TextInputLayout and EditText

As said before, TextInputLayout wraps the EditText so that it controls the EditText behaviour. Let us suppose we have three different EditText and three TextInputLayout. Focusing the attention to the first one of this EditText, this one has to be wrapped by TextInputLayout so that we can have the floating label.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    xmlns:app="" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    tools:showIn="@layout/activity_main" tools:context=".MainActivity">

    android:layout_height="wrap_content" android:id="@+id/til1">








android:hint is the floating label that is managed the TextInputLayout. With this layout and a simple activity,  it is possible to obtain the app shown above.

Android Form Validation

Another interesting use of the TextInputLayout is in the form validation. As told before, this component handles error messages so that they appear near the EditText.
This feature is very useful when the app have to validate some data inserted by user. To show how to use TextInputLayout to handle EditText error we can suppose to have a simple form with a submit button as shown in the picture below.

When user pushes the button the app validate the result and if something goes wrong, the app shows the error message near the EditText that caused it.
To handle the errors, TextInputLayout provides two methods: setError that accepts a string that contains the message and setErrorEnabled that accepts a boolean to enable or disable the error functionality. The first method is used to show an erorr message, the second to remove the message.
The Activity that handles the UI contains validation method, like the one shown below:

     edtName = (EditText) findViewById(;
     edtSurname = (EditText) findViewById(;
     edtPhone = (EditText) findViewById(;
     nameLayout = (TextInputLayout) findViewById(;
     surnameLayout = (TextInputLayout) findViewById(;
     phoneLayout = (TextInputLayout) findViewById(;

     Button btn = (Button) findViewById(;
     btn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             if ( validateData() ) {

In the validate method:

   private boolean validateData() {
        boolean result = true;

        String name = edtName.getText().toString();
        if (name == null || name.length() < 3) {
            // We set the error message
            result = false;
            // We remove error messages

        String surname = edtSurname.getText().toString();
        if (surname == null || surname.length() < 3) {
            // We set the error message
            result = false;
            // We remove error messages

        String phone = edtPhone.getText().toString();
        if (phone == null || phone.equals("")) {
            result = false;
        else if (phone.equals("0")) {
            result = false;

        return result;

In this post, you have learnt how to create a material UI using TextInputLayout to animate EditText and how to handle error using the combination of TextInputLayout and EditText.

Read More..

Getting started with Android app and material design:Toolbar and Navigation drawer

By With No comments:

How to develop an Android app with material design guidelines using Toolbar and Navigation drawer

Topics covered

Android material design

Android tooolbar

Android navigation drawer

Material design is a set of rule built by google that guide how to develop an Android app. They can be applied not only on the Android app but also on web site design. In the process of development of an app, Android provides some libraries that help developers to implement the main material guide line rules. The most important libraries are:
After all, these two libraries are imported by default when a developer starts a new project using Android Studio.

One important aspect in an app is represented by color schema. Material design rules describes how to chose colours.
Let us suppose we create a simple Android project and let us follow the main step to implement a Android app following Material design rules.

Material design:Colours

The first step, is choosing the colour schema for our app. To this purpose there is a great website that can be used to create the colour schema according to material design rules.
After the colours are selected we can download colors.xml:

    <color name="primary">#3F51B5</color>
    <color name="primary_dark">#303F9F</color>
    <color name="primary_light">#C5CAE9</color>
    <color name="accent">#03A9F4</color>
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#727272</color>
    <color name="icons">#FFFFFF</color>
    <color name="divider">#B6B6B6</color>

You can select the schema you like. The first result is shown in the picture below:

how to use android toolbar with material design

Now it is time to create our theme that uses the colours we selected before. The app should support the largest number of smart phones not only those running Lollipop or later.
For this reason it is necessary to create two themes one for the devices that run Android 5 or later and those that run pre-lollipop version.
So let us create two directory under values:


The first one is used by all smart phones running pre-Lollipop version while the second folder is used by smart phones with OS starting from Lollipop.
In the first directory let us style.xml:

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">    
        <item name="colorPrimary">@color/primary&lt/item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
    <style name="MyAppTheme" parent="@style/AppTheme" />

while in the second directory we simply add:

   <style name="MyAppTheme" parent="AppTheme">
     <item name="android:windowContentTransitions">true</item>
     <item name="android:windowAllowEnterTransitionOverlap">true</item>
     <item name="android:windowAllowReturnTransitionOverlap">true</item>
     <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
     <item name="android:windowSharedElementExitTransition">@android:transition/move</item>

Finally in the Manifest.xml modify the file:
        android:theme="@style/MyAppTheme" >

Android Toolbar

One of the most important component in developing an Android app is the Toolbar. The toolbar plays the role that was played before by Android action bar.The toolbar can be used to hold:

  • Navigation button
  • App tile and subtitle
  • Action menu
  • Brand logo
According to material design the Toolbar have the primary color we selected before. How to add it to Android app?

<RelativeLayout xmlns:android=""
    xmlns:tools="" android:layout_width="match_parent"

   <include layout="@layout/toolbar" />


where toolbar layout is:
< xmlns:android=""
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Notice at line 5 we set the default height of the toolbar using ?attr/actionBarSize and at line 6 the toolbar background.
In the activity it is necessary to set the toolbar:

protected void onCreate(Bundle savedInstanceState) {
private void setToolBar() {
    Toolbar tb = (Toolbar) findViewById(;
    ActionBar ab = getSupportActionBar();

Running the example we get:

Toolbar with material design

Add action menu to Toolbar

Once the is configured correctly, it is possible to add action menu or menu items that appear on the Toolbar, to do it under res/menu add a file called main_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""

    <item android:id="@+id/menu_settings"

    <item android:id="@+id/menu_help"
        android:orderInCategory="110" />

    <item android:id="@+id/menu_compass"


Now in the activity there is:

public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(, menu);
  return true;

Running the example the app looks like:

options in android toolbar

When user select one of this item the app should be detect it and take the right action, to do it it is necessary to override a method:
public boolean onOptionsItemSelected(MenuItem item) {
   int itemId = item.getItemId();
   String btnName = null;

   switch(itemId) {
        btnName = "Settings";
        btnName = "Compass";
        btnName = "Help";

  Snackbar.make(layout, "Button " + btnName, Snackbar.LENGTH_SHORT).show();
  return true;
In this case we simply show a info message using a Snackbar.

Android Navigation drawer

Navigation drawer is one of the most import UI pattern introduced by Google in developing Android app.Navigation drawer is a side menu that helps to organise the navigation inside the app. It is a uniform way to access different pages and information inside the app. You can refer to official google page to know more. The implementation is very easy. The custom view that represents the navigation drawer must be the first element in the layout:
<?xml version="1.0" encoding="utf-8"?>


        <include layout="@layout/toolbar" />

        <!-- Let's add fragment -->


        app:menu="@menu/nav_items" />
In this case the toolbar is inside a LinearLayout but the way the app handles it is the same shown before. In this case there is a FrameLayout to hold the page content shown through fragments. The NavigationView is the "real" menu of our app. The menu items are written in nav_items.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="">
    <group android:checkableBehavior="single">
        <item android:id="@+id/fab"
              android:title="Floating Action Button"
              android:icon="@drawable/ic_action_fab" />

        <item android:id="@+id/star"
            android:icon="@drawable/ic_action_star" />

        <item android:id="@+id/uploadr"
            android:icon="@drawable/ic_action_upload" />
To handle when user clicks on an item is very easy, it is necessary to write:
    private void setNavigationDrawer() {
        dLayout = (DrawerLayout) findViewById(;
        NavigationView navView = (NavigationView) findViewById(;
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                Fragment frag = null;
                int itemId = menuItem.getItemId();

                if (itemId == {
                   frag = new Fragment1();
                else if (itemId == {
                    frag = new Fragment2();

                if (frag != null) {
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                    transaction.replace(, frag);
                    return true;

                return false;
We simply add a listener to know when one of the menu item is pressed by user and then set the right fragment. The last step is opening the drawer when user clicks on the home icon, to do it:

   public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        String btnName = null;

        switch(itemId) {
            // Android home
            case {
                return true;
Running the example app we have:

Apply material design to android navigation drawer

At the end in this post, you know how to use Android navigation drawer and toolbar according to material design guide lines.

If you want to know how to create a real app using material design give a look at this link describing how to create a weather app in android with material design.
Source code available @github.

Read More..

Tips for Developing an Android App: My Lessons Learned

By With No comments:
Topics covered

Understand Android market

Tips for developing Android app

Lessons learned

Nowadays, Android is not just on tens of thousands of different phones and tablets. It’s on your wrist, in your living room, in your car, and as soon we start assigning IP addresses to inanimate objects, it is going to be pretty much everywhere around us. A lot of ground for even an experienced Android developer to cover! Also there are over one million apps just on Google Play, not counting Amazon AppStore or markets we are not generally interested in, like China. So, how can an independent developer create a successful app in this huge market with big players? I have no idea, I haven’t made a successful app! But, I have made a cute one, and I’d like to share my story with you.

Lesson 1: Connect The Dots

Success (usually) doesn’t happen overnight and this is not my first app. I have ones ranging from unexpected over-the-weekend development hits like Macedonian Orthodox Calendar, with over 30,000 users in a language that no more than 4 million people can understand, to more successful failures like TweetsPie, an app with heavy media coverage and a terrible user-base of just over 600 active users. A lot of lessons there! While these apps helped me understand the mind of the “elusive creature called the User” a bit better, the one that inspired me was a two-hour project. Originally developed to make me a millionaire, once 1,428,571 users purchased the app as Google takes 30 cents out of every dollar, The Dollar App was made to test my merchants account. Little did I know that years later I will receive an email from a happy mom stating that it was the best dollar that she ever spent since her boy was smiling every time my app gave him a hug. Android app development for beginners can be simple and fun when scaled effectively. And that’s how an idea was born! Why not use the fundamental human need for a hug and make it pretty? Make it for a specific audience, interactive, challenging, fun to use, and even more fun to share.

Lesson 2: Understand The Android Market

All the things I mentioned above added up to a live wallpaper app. The basics are not that hard to guess. Android has a bigger market share than iOS, but iOS users purchase more. Messaging apps are wildly popular, but freemium games top the earnings. China, India, Brazil and Russia are emerging markets, but lack spending habits. You can read the App Annie Index for more insights. So how does a live wallpaper app fit into this? First of all, it eliminates most of the platforms since a live wallpaper is an Android thing. Second, this feature was added in Android 2.1 so it has a large community and quite a few beautiful examples. Most notably Paperland and Roman Nurik’s open source Muzei, probably the best reference point for Android development. While there are lot of live wallpapers out there, most of them fall under the scenic/weather category, and very few fall under the cuteness overload category. This is something we wanted to change and offer something that gives you a smile each time you unlock your phone, even though you unlocked it for a completely different reason. We gave you a cute little bundle of joy to hug you before you go to bed at night, or when you turn off your alarm in the morning. And even better, make it personal and customizable. Without further ado, and before we go into technical details, I proudly present you: Ooshies - The Live Wallpaper Ooshies is the name of my Android app. It may not have been successful but it helped me learn the lessons needed to write this guide for beginner Android developers.

It features:
  • free live wallpaper app that gives you hugs
  • 12 unique ooshies to choose from
  • free, un-lockable, and purchasable content
  • current weather updates
  • social login and data sync
  • seasonal greetings
  • many surprises
  • a ninja cat
  • did we mention hugs?
Successful Android apps sometimes just make you smile.

Lesson 3: Try To Make It Happen

Ooshies seemed like a pretty straightforward Android app idea. Paint a background, overlay some clouds and stars, put a bear with a balloon on top, and you are good to go. But no, it’s Android! What seems easy is often quite difficult and we tend to repeat the same common mistakes over and over again. Here’s a quick rundown of the challenges I faced:
  1. Hardware acceleration - why draw using the CPU when the GPU is so much better at it? Well, it turns out that drawing bitmaps on a canvas cannot be hardware accelerated. At least not for the time being.
  2. OpenGL - if we want hardware acceleration we need to use OpenGL ES or even better a framework that does most of the work for us.
  3. Bitmap loading - a well known memory consumption issue. We need to allocate 1 byte [0-255] of memory, for each channel in the #ARGB, to display a single pixel. Also the images we use often have higher resolutions than the device’s display. Loading them all will quickly result in OutOfMemroyException.
  4. Home launchers - the live wallpaper will be hosted in the home launcher process, and different launcher tend to give different callbacks to the live wallpaper service (most notably Nova and TouchWiz).
  5. Battery life - if not done right, the live wallpapers and the widgets can drain a lot of battery. With all the buzz about the Lollipop (Android 5.0) terrible battery life the first app to go will be the live wallpaper.
So, overlaying a bitmap, painting it on a canvas, and then switching frames on touch to give a hug, doesn’t seem like a big deal, even when if it is done on the CPU, right? Thats right, it’s not a problem. But, who wants a static live wallpaper? It beats the purpose. The wallpaper should respond to your touches, it should move as you scroll your home screens, it should perform random acts of kindness and make you feel happy. And there is an Android development trick for that. There is a term called the parallax effect for adding depth in a 2-dimensional space. Imagine yourself driving a car. The house closer to you moves faster than the mountain in the distance. Same effect can be achieved by moving objects in different speed on a canvas. Although, they are all in the same plane, your brain perceives the faster moving objects as closer to you. Much like adding drop shadows, the parallax effect adds a z-axis. And this is where all hell breaks loose! On most devices moving the Ooshie, the weather overlay, and the background, at different speeds, yields significant frame rate drop. Here’s how a single frame is drawn:
    canvas.drawBitmap(background, 0 - offsetX / 4, 0, null);
    canvas.drawBitmap(weatherOverlay, 0 - offsetX / 2, 0, null);
    if (!validDoubleTap) {
      canvas.drawBitmap(ooshieNormal, positionX - offsetX, positionY, null);
    else {
      canvas.drawBitmap(ooshieTapped, positionX - offsetX, positionY, null);
The offset is a percentage of the distance user has scrolled. It’s a callback that the wallpaper engine provides:
    public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep,
                                 int xPixelOffset, int yPixelOffset){
      super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
      // athe current offset should be a fraction of the screen offset to achieve parallax
      if (!isPreview()) {
        float newXOffset = xOffset * 0.15f;
        if (isVisible() && hasActiveSurface) {

I must note that all of this would be unnecessary if I knew how to work with OpenGL! It’s on my TODO list, since anything more complex than what we have now will require a hardware acceleration. But, for the time being I have to work harder, not smarter (I’m open to suggestions in the comments). So here’s what we did:

Lesson 4: Work With What You Have

As a big supporters of the minSdk=15 initiative, from the start we eliminated all the 2.x devices. The effort for maintaining backward compatibility is greater than the possible revenue from users unable\unwilling to upgrade their phones. So, in most cases, we’ll be able to achieve smooth experience with an added option to disable the parallax if desired. Per this Android development guide, I wanted to give the option to disable the parallax. Another big optimization is how we handle the bitmaps. A very similar parallax effect can be achieved with drawing two bitmaps instead of three:
  1. Ooshie overlay - trimmed and carefully scaled Ooshie bitmap (can be accessorized)
  2. Combined overlay - a combined background and weather bitmap that moves with a fraction of the Ooshie speed
This Android development trick saves memory and speeds up the drawing time, for a slight parallax effect degrade. When scrolling the home screens, frames will be drawn quite often (ideally more than 30 times per second). It’s crucial not to draw them when the home screen is not visible (some lock screens, some app drawer, opening/switching apps etc.) to minimize the CPU usage. This is all tied closely with the weather updates. Initially there was a repeating task, executing every hour or two, to sync the weather, but it was really an overkill. If the user cannot see the wallpaper, the weather info is irrelevant. So now, weather updates happen only when wallpaper is visible.
    long lastUpdate = prefStore.getLong(SharedPrefStore.Pref.WEATHER_TIMESTAMP);
    if (System.currentTimeMillis() - lastUpdate > Consts.WEATHER_UPDATE_INTERVAL){
        // update the weather if obsolete
        Intent intent = new Intent(getApplicationContext(), WeatherUpdateService.class);
So, basically, here’s the checklist for a memory optimized smooth software bitmap drawing:
  1. Combine bitmaps once
  2. Draw less bitmaps
  3. Redraw only on demand
  4. Avoid background tasks
  5. Offer users some control over the process

Lesson 5: Test. Test. Test

I cannot stress how important this is! Never, I repeat NEVER, release your app before testing it! And, I don’t mean that YOU should do the testing. You wrote the code, you know how it works, and you influence the result by knowing the expectations. I’m not talking about JUnit testing (although recommended), but about staged rollouts i.e. alpha and beta testing. If you are into Android software development the terms are straightforward, but here is a quick rundown:
  1. Alpha testers - a small group of people consisting of your teammates and people from the industry, preferably Android developers. Chances are they are going the have high-end devices and will play around with the developers options. They’ll send you stack traces, bug reports, and even give you some code/UI optimization tips and tricks. Perfect for early releases with partial/missing features.
  2. Beta testers - a much broader audience with various demographics. Stable releases should be published here. Even if your ninja level is too damn high, you can never predict, let alone account, for all the possible Android distributions and ways people use their phones.
Once we passed the alpha, I thought we were done. But, boy I was wrong?! Turned out that not all Android users have Nexus devices with the latest software! Who’d know? :) Here are some Android development issues based on this revelation:
  1. Different launchers have different default home screens - usually the first or the middle one, and ,as far as I know, there is no way of knowing it’s position.
  2. It’s hard to center the Ooshie without knowing the default home screen position - thus the settings slider for adjusting the parallax offset.
  3. An average user doesn’t know what parallax offset means - much simpler terminology should be used on the settings page.
  4. A random user will suggest your next feature.
So I would like to thank all our beta testers for the hard work they did. I hope that getting all the latest features before anyone else is a decent reward for their dedication. If you’d like, you can also be a part of our Google+ Beta Community. Beta testing is a critical step for Android beginners to keep in mind as they begin programming their successful Android apps.

Lesson 6: Let The Data Speak

Making an Android app that stands out today is a bit more difficult than making a calculator app, when there were none back in 2009. Making the perfect app is hard. Mainly because perfection is in the eye of the beholder. What is good for me, doesn’t necessarily mean it’s good for you. That’s why it’s important to let the app grow. Our roadmap checklist for new features shows that we have enough work for the whole 2015. Among other things we’ll soon include:
  1. Sounds
  2. Seasonal backgrounds
  3. Customizations (background color, weather packs, ooshie skins, etc.)
  4. Region specific ooshies (ex. babushkas)
  5. A lot of new ooshies and ways to unlock them
Now, we might have kept the app in beta until all is done, but that way we are throwing away valuable data. Not all beta testers will dedicate a portion of their day to send you the feedback. That is where you can benefit in using tools for getting the feedback. You can use Google Analytics, Flurry, Mixpanel, Crashalytics, ACRA, etc. to collect usage data. For example, by analyzing the data we noticed that users don’t click the settings button a lot, so we made it more apparent and added a quick tutorial for tweaking the settings. Although this is a background process, it can be used to further improve the user experience. Why not show the user how many times:
  1. he/she received a hug
  2. how many rainy days were brightened up by a smile
  3. how many taps were needed to unlock an Ooshie with a mini-game
  4. how many friends installed the app because of you
Every Android development guide should tout the importance of Google Analytics in optimizing your app!
This is important because it provides consequences for their actions. Don’t make the same mistake our educational system does, making the users passive content consumers. Make them in charge. Give them the option to control their own devices and create their own personal experience. If you manage to package all this into a cute bundle that steals a smile on the first splash, than is not too far fetched to ask the user for spammy favors for content unlocking. In the end, you need to evolve your Android app development based on this data as a guide. Although primarily intended for moms/kids, this app may become popular in other demographics. It may not fit into our original vision, but users needs must be met. Otherwise they’ll find someone who can.


Let’s return to my most successful failure TweetsPie. Despite couple of awards and huge media coverage, the app failed to retain it’s users (the reasons why are beyond the scope of this article). Success is not always apparent. Thanks to the whole experience I learned a lot. I gave, at least, a dozen lectures on How (not) to fail as a startup on various events and hackathons, and managed to get a couple of clients at Toptal. Even more important, I try not to repeat the same Android development mistakes with Ooshies by following the tips and tricks in this guide. To wrap up this long guide, what we define as a success is, at later stage, tightly coupled with what we set as goal in the beginning. The most common success measure is, of course, making a lot of money. No matter if your app makes it or not, you must try to make it happen, and believe me at the end you’ll become a better person (hopefully one that manages to learn OpenGL). You’ll make new friends, few enemies, and if you are lucky/smart enough you’ll make a lot of users happy. You can check our website or download Ooshies to give it a try.

Published with permission of toptal

Read More..

IoT project: Arduino sends push notification to Android using Temboo,

By With No comments:

This post describes how to create an IoT project that uses Arduino to send push messages to Android smart phones using Temboo and

Topics covered

Android push message

Arduino board

Internet of things project

Temboo and

As example, we will build an alarm system based on Arduino and Android, this is an interesting example of Internet of things (IoT) and the aim of this project is building an alarm using an infrared sensor (PIR) connected to Arduino board that sends push messages to Android smart phone. This project mixes different technologies and platforms and we make them working together!
The alarm system uses two platforms that help simplyfing the project:
  • Temboo 

IoT Project overview

Before diving into the project it is useful to describe these two platforms.
Temboo is a platform that has a set of “connectors” that can be used to exchange data with other platforms or service providers (i.e eBay, Yahoo! Weather, Google and so on). The interesting part of Temboo is that it is compatible with Arduino board, so that these connectors can be exported on Arduino. is the platform we used in the last post to send android push messages.

The main overview of the internet of things project is shown below:

Arduino alarm system using PIR sensor and send push notification to smart phone

As it is clear, there are several parts that build the IoT project. The first part is Arduino board with PIR sensor that is used to detect movements. Arduino runs a Temboo agent that sends data to Parse platform. This agent is triggered when one of the Arduino digital input gets HIGH. The Temboo platforms is used to create the agent without writing too much code lines. Using Temboo choreo, Arduino can send JSON data directly to that in turns send a push message to our smart phone.

Arduino Sketch

The first step is setting up the Arduino sketch that uses PIR sensor and test it. This step is very simple, we have to connect the sensor to Arduino board using three wires: Power, Ground and Signal.
The sensor is very simple, the output gets high when it detects movements. For this example we can suppose it is connected on digital pin 8.
To check that our sensor works correctly and it is connected in the right way to Arduino board so that it detects movements,  try to load this code into arduino:

int stato = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(8, INPUT);

void loop() {
  // put your main code here, to run repeatedly:
  stato = digitalRead(8);


Now runs the code and move your hand in front of the sensor and give a look at the serial monitor to check if it works!
Now the Arduino component is ready!

Temboo choreo

The next step is setting up the agent that connects Arduino board to In this case, we need a Ethernet shield to connect Arduino to internet. I've used Wiznet W5500. Once you have created your account, it is time to configure your Temboo chores. We want to connect Arduino to Parse so we check Parse -> Push Notification. Parse choreos requires some information before using it:
  • Application ID
  • RestAPI Key
These two parameters are used to connect the agent to You can find these info in connection api parameters

 You have to copy the required key into Temboo:

Temboo choreos config

Ok we are ready. If you want you can try to send a notification from Temboo to
Now set the trigger that control the agent:

Temboo agent trigger

At the end Temboo will create the Arduino code ready to use!! finally copy and paste the code into your Arduino IDE.
The code generated by Temboo is shown below:

#include <spi.h>
#include <dhcp.h>
#include <dns.h>
#include <ethernet.h>
#include <ethernetclient.h>
#include <temboo.h>
#include "TembooAccount.h" // Contains Temboo account information

byte ethernetMACAddress[] = ETHERNET_SHIELD_MAC;
EthernetClient client;

// The number of times to trigger the action if the condition is met
// We limit this so you won't use all of your Temboo calls while testing
int maxCalls = 10;

// The number of times this Choreo has been run so far in this sketch
int calls = 0;

int inputPin = 8;

IPAddress ip(192, 168, 1, 130); // Arduino IP Add

void setup() {
  // For debugging, wait until the serial console is connected

 Ethernet.begin(ethernetMACAddress, ip) ;


  // Initialize pins
  pinMode(inputPin, INPUT);

  Serial.println("Setup complete.\n");

void loop() {
  int sensorValue = digitalRead(inputPin);
  Serial.println("Sensor: " + String(sensorValue));

  if (sensorValue == HIGH) {
    if (calls < maxCalls) {
      Serial.println("\nTriggered! Calling SendNotification Choreo...");
    } else {
      Serial.println("\nTriggered! Skipping to save Temboo calls. Adjust maxCalls as required.");

void runSendNotification(int sensorValue) {
  TembooChoreo SendNotificationChoreo(client);

  // Set Temboo account credentials

  // Set profile to use for execution
  // Set Choreo inputs
  String NotificationValue = "{\"channel\": \"temboo\", \"type\": \"android\", \"data\": {\"message\": \"This is a test alert!\"}}";
  SendNotificationChoreo.addInput("Notification", NotificationValue);

  // Identify the Choreo to run

  // Run the Choreo
  unsigned int returnCode =;

  // Read and print the error message
  while (SendNotificationChoreo.available()) {
    char c =;

Configure channel and build Android app

Temboo requires we use a Parse channel to send our notifications. We have then to modify our Android app to use a channel to listen to incoming notification. If you don't know how to write an android app that handles push messages you can read my previous post describing how to send android push messages with

Modify slightly the in this way:

    public void onCreate() {
        Parse.initialize(this, "sfFzOxotpsdOHWJE3nMmD0erLgFoecttKvC9CzIc", "nwbMEy7l4STpyNrABdrQxpEjdKIynSbuec56QbEz");


where temboo is the channel.
We are ready!! Runs the app and move your hand near the sensor, Arduino will send a push message to the Android smart phone!!
The final result is shown here:

Android push message sent by Arduino with Temboo and

At the end of this post, you know how to build an IoT project using Arduino and Android and how to integrate these two ecosystems through Temboo and

Read More..

Android push notification tutorial using

By With No comments:

In this tutorial you will learn how to send push notification is Android. Android push notification is a service used to send messages directly to the Android smart phones

Topics covered

Android push message

Push message

Parse push service

Push custom recevier

Google Android push notification is a service used by developers to send data to Android apps as soon as the data is available: in this way Android app doesn't have to make requests to the server to know if new information are available.
Using Android push service, apps can save smartphone battery and reduce the network traffic: the user experience is also improved.
There are several different methods that can be used to implement Android push messages, the standard way is using GCM (Google Cloud Messaging) but there are some alternatives very interesting like, that is easier to use.

Android push notification example: Set up project with

The first thing is creating a Parse account and configure a new app. This is very easy. Once you have all things done, it is time to create a new project in Android Studio and modify build.grade to include the parse library:

dependencies {
    compile 'com.parse.bolts:bolts-android:1.2.1'
    compile 'com.parse:parse-android:1.10.1'

Now you can follow, the tutorial provided by In our case, we have created a ParseTutorialApplication that extends Application and it is used to configure the Parse connection:

public class ParseTutorialApplication extends Application {

    public void onCreate() {
        Parse.initialize(this, "your key", "your key");

By now you use the default receiver provided by the library, in the next paragraph you will see how to customise it.
If the project is configured correctly, you can try to send a android push notification using the web interface:

android push text message

In your Android emulator, you should get the push notification:

android push notification with text message

Please be sure that the emulator includes Google API.

Custom receiver example : Receive JSON data

Now it is time to customise the receiver so that we can support custom as android push notification message and not only text messages. Customising the receiver, it is possible to implement custom app logic like parsing the incoming message and show custom messages and so on. Looking back in the Manifest.xml, as broadcast receiver it was used the standard receiver com.parse.ParsePushBroadcastReceiver, now to customise its behaviour we can subclass it:

public class JSONCustomReceiver extends ParsePushBroadcastReceiver {
    protected void onPushReceive(Context context, Intent intent) {

and override the onPushReceiver so that it is possible to implement the app logic when the message is available.
Let us suppose that the message is in JSON format like that:

{"message":"hello phone"}
In the onPushReceiver, the app parses the message:
private String getData(String jsonData) {
        // Parse JSON Data
        try {
            System.out.println("JSON Data ["+jsonData+"]");
            JSONObject obj = new JSONObject(jsonData);

            return obj.getString("message");
        catch(JSONException jse) {

        return "";
Once the message content is available and extracted from JSON message, the app notifies it to the user using NotificationCompat and NotificationManager.

// Create custom notification
NotificationCompat.Builder  builder = new NotificationCompat.Builder(context)
  .setContentTitle("Notification from Parse")

Notification notification =;
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

where pendingIntent is the instance of the Intent that starts the Activity when user touches the push notification:

// Add custom intent
Intent cIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
                              cIntent, PendingIntent.FLAG_UPDATE_CURRENT);

and finally the app notifies the message:

nm.notify(1410, notification);

The final result is shown in the picture below:

Android push notification son message with custom receiver

Notice we have customised the notification icon too.
At the end of this post you know how push notification works and how to implement push notification android app using
In the next posts you will learn how to use push notification generated by smart controllers like Arduino!
Source code available @ github

Read More..
Copyright © 2015 Surviving with android | All Rights Reserved. Design By Templateclue