Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 6 ■ IOT PATTERNS: REMOTE CONTROL

MQTT broker when the user taps on the app screen. Finally, disconnect the app from the
MQTT broker, as you do not need an active connection throughout.
Now that the MQTT connectivity and publish code is ready, you are going to go back
to the MainActivity class and update the onCreate() method. Earlier you had added
a listener to the light icon that would be called whenever a user taps on the app screen.
You are going to provide the missing implementation of the listener. You are just going
to initialize a new MQTTClient object and call its publishToMQTT() method inside the
listener. Listing 6-10 provides the complete code of the MainActivity class within the
onCreate() method highlighted.


Listing 6-10. Complete Code of MainActivity.java


package com.codifythings.lightingcontrolsystem;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {


private static final String TAG = "MainActivity";


@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) {
try {
new MQTTClient().publishToMQTT();
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
});
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it

Free download pdf