CHAPTER 5 ■ IOT PATTERNS: REALTIME CLIENTS
For now you are going to add two new methods. The first method is provided in
Listing 5-15. It’s updateView(...) and will update the screen with new messages from the
sensor.
Listing 5-15. Add the updateView(...) Method to MainActivity.java
public void updateView(String sensorMessage) {
try {
SharedPreferences sharedPref = getSharedPreferences(
"com.codifythings.motionsensorapp.PREFERENCE_FILE_KEY",
Context.MODE_PRIVATE);
if (sensorMessage == null || sensorMessage == "") {
sensorMessage = sharedPref.getString("lastSensorMessage",
"No Activity Detected");
}
final String tempSensorMessage = sensorMessage;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView updatedField = (TextView)
findViewById(R.id.updated_field);
updatedField.setText(tempSensorMessage);
}
});
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("lastSensorMessage", sensorMessage);
editor.commit();
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
The second method is provided in Listing 5-16. It is createNotification(...) and
will create a realtime notification on a phone or tablet to alert the users.
Listing 5-16. Add the createNotification(...) Method to MainActivity.java
public void createNotification(String notificationTitle,
String notificationMessage) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.notification_template_icon_bg)
.setContentTitle(notificationTitle)
.setContentText(notificationMessage);