Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 6 ■ IOT PATTERNS: REMOTE CONTROL


Listing 6-6. Default Code for MainActivity.java


public class MainActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) { ... }


@Override
public boolean onCreateOptionsMenu(Menu menu) { ... }


@Override
public boolean onOptionsItemSelected(MenuItem item) { ... }
}


Since you removed toolbar and floating action button from activity_main.xml , you
need to remove the reference in the onCreate method as well.
You want the light bulb icon to be interactive so that when an app user taps on the
icon, a message is published to the MQTT broker. To accomplish this, you need to update
the onCreate() method , as shown in Listing 6-7. You are going to register an onClick()
listener which will be called whenever someone taps on the light bulb icon. For now the
implementation of onClick() is empty and will be updated later.


Listing 6-7. Screen Tap/Click Listener Code


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


ImageView lightIcon = (ImageView) findViewById(R.id.light_icon);
lightIcon.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//TODO - add action
}
});
}


MQTT Client


The final piece of this app is the MQTT client that will connect to an MQTT server and
publish to the codifythings/lightcontrol topic.
In order to communicate with an MQTT broker, your app requires an MQTT library
that can be download from https://eclipse.org/paho/clients/java/.

Free download pdf