COMP61242: Task /04/18

Similar documents
CSE 660 Lab 7. Submitted by: Arumugam Thendramil Pavai. 1)Simple Remote Calculator. Server is created using ServerSocket class of java. Server.

Android UI Development

Tabel mysql. Kode di PHP. Config.php. Service.php

<uses-permission android:name="android.permission.internet"/>

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

Getting Started With Android Feature Flags

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs

Our First Android Application

Software Practice 3 Before we start Today s lecture Today s Task Team organization

Lab Android Development Environment

EMBEDDED SYSTEMS PROGRAMMING Android Services

INTRODUCTION TO ANDROID

Android Application Development. By : Shibaji Debnath

Android Workshop: Model View Controller ( MVC):

Android - JSON Parser Tutorial

MAD ASSIGNMENT NO 3. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

COMP4521 EMBEDDED SYSTEMS SOFTWARE

Vienos veiklos būsena. Theory

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices.

Applied Cognitive Computing Fall 2016 Android Application + IBM Bluemix (Cloudant NoSQL DB)

Basic GUI elements - exercises

University of Stirling Computing Science Telecommunications Systems and Services CSCU9YH: Android Practical 1 Hello World

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.

Fragment Example Create the following files and test the application on emulator or device.

Create Parent Activity and pass its information to Child Activity using Intents.

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015

Android Tutorial: Part 3

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Mobile Programming Lecture 1. Getting Started

Android HelloWorld - Example. Tushar B. Kute,

Upon completion of the second part of the lab the students will have:

ITU- FAO- DOA- TRCSL. Training on. Innovation & Application Development for E- Agriculture. Shared Preferences

Android Beginners Workshop

Produced by. Mobile Application Development. Eamonn de Leastar

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Introduction to Android Development

Created By: Keith Acosta Instructor: Wei Zhong Courses: Senior Seminar Cryptography

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard.

IEMS 5722 Mobile Network Programming and Distributed Server Architecture

Solving an Android Threading Problem

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Intents. Your first app assignment

Mobile Software Development for Android - I397

EMBEDDED SYSTEMS PROGRAMMING Application Basics

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

Tutorial: Setup for Android Development

UNDERSTANDING ACTIVITIES

PROGRAMMING APPLICATIONS DECLARATIVE GUIS

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2

Embedded Systems Programming - PA8001

API Guide for Gesture Recognition Engine. Version 2.0

Real-Time Embedded Systems

Android Programs Day 5

10.1 Introduction. Higher Level Processing. Word Recogniton Model. Text Output. Voice Signals. Spoken Words. Syntax, Semantics, Pragmatics

Android - Widgets Tutorial

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

XML Tutorial. NOTE: This course is for basic concepts of XML in line with our existing Android Studio project.

android-espresso #androidespresso

Hello World. Lesson 1. Create your first Android. Android Developer Fundamentals. Android Developer Fundamentals

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface?

Data Persistence. Chapter 10

Wireless Vehicle Bus Adapter (WVA) Android Library Tutorial

Assignment 1: Port & Starboard

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2.

M.A.D ASSIGNMENT # 2 REHAN ASGHAR BSSE 15126

LifeStreet Media Android Publisher SDK Integration Guide

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

Learn about Android Content Providers and SQLite

Android Basics. Android UI Architecture. Android UI 1

Android Services. Victor Matos Cleveland State University. Services

Developed and taught by well-known Contact author and developer. At public for details venues or onsite at your location.

Lab 1 - Setting up the User s Profile UI

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

An Overview of the Android Programming

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs

ANDROID PROGRAMS DAY 3

Notification mechanism

ANDROID USER INTERFACE

Android Application Development

SD Module-1 Android Dvelopment

PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE)

TextView Control. EditText Control. TextView Attributes. android:id - This is the ID which uniquely identifies the control.

Lab 1: Getting Started With Android Programming

Fragments. Lecture 11

Android/Java Lightning Tutorial JULY 30, 2018

Thread. A Thread is a concurrent unit of execution. The thread has its own call stack for methods being invoked, their arguments and local variables.

Software Practice 3 Today s lecture Today s Task

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)


Java & Android. Java Fundamentals. Madis Pink 2016 Tartu

Embedded Systems Programming - PA8001

Lab 3. Accessing GSM Functions on an Android Smartphone

ELET4133: Embedded Systems. Topic 15 Sensors

A Crash Course to Android Mobile Platform

M.A.D Assignment # 1

Transcription:

COMP61242: Task 2 1 16/04/18 1. Introduction University of Manchester School of Computer Science COMP61242: Mobile Communications Semester 2: 2017-18 Laboratory Task 2 Messaging with Android Smartphones The aim of this task is to become familiar with Android development and emulation facilities for developing and testing applications. Ultimately these applications can be downloaded to real smart-phones via a USB connection. The application we aim to produce is a messaging system capable of exchanging, firstly, strings of text, secondly recorded text messages, images and MP3 files, and finally real time speech. Task 2 is concerned with introductory material and Task 3 will follow on with more advanced parts of the application. The communication will take place via SIP-like proxy servers running some pre-developed software on PCs. The communications will ultimately be wireless using WiFi, but initially it will be by wired Ethernet between Android emulators and the proxy-servers. Such an application could be useful in ad-hoc or emergency situations where the normal communications infrastructure has failed and standard global messaging services cannot be accessed. The proxy-servers will provide registration, communication with a location-server (DNS) and protocols for inviting, accepting and acknowledging call set-up initiatives. To simplify the PC software, there will a single proxy server with a built-in location-server. Proxy Server Register, Invite, Accept, Ack etc. Invite, Accept Ack, etc. Location server Proxy Server Register, Invite, Accept, Ack etc. Barry Channel simulator Jeff Rather than setting up a peer-to-peer link for direct message and speech communication, you will eventually (in Task 3) communicate via a channel simulator running alongside the proxy server. Initially, this will be a benign lossless connection, but later, it may start to introduce

COMP61242: Task 2 2 16/04/18 bit-errors. Worse still, there may be security attacks and eavesdroppers trying to intercept and disrupt the communication. Do not worry about this in Task 2, and keep things simple by using the MSG command to send messages (see the list of Proxy Server commands later). 2. Android Development To begin with, you will need to become familiar with the Android development and simulation facilities. There are many options for both Linux and Windows users. All the necessary software is open-source and can be downloaded in the laboratory or even at home. In our laboratory, we have an integrated development environment (IDE) package known as Android studio. 2.1. Android Studio is the IDE made available by Google for developing Android applications. It is relatively new software and may contain bugs. However, this should not come as a huge surprise to Computer Science students. We have found Android Studio much easier than Eclipse to learn and use, and are therefore recommending this option despite the fact that there are some work-arounds needed to get it working correctly on the laboratory machines. When using your own computer at home, you should not have too many problems using this IDE. Android Studio provides editing and file-management facilities for developing Android projects. It links to the Android software development kit (SDK), the Java development kit (JDK), and other libraries. The Android SDK also contains the software needed to emulate mobile phones as a means of debugging and evaluating Android software on the PC itself. To start android studio on a University machine type: "start_android_studio.sh 61242" 2.2. Android Studio sample project First, create a very basic Android sample ( dummy ) project which simply displays hello world on a smartphone. To do this after launching Android Studio on your PC, select 'New Project'. Then just accept the default options which request Android Studio to create a folder containing a number of files. This folder, with its many files, is the dummy project. It may then be built to produce an application that may be run on a mobile phone. After selecting the default options, you will see a window that says something like "Building 'MyApplication' Gradle project info". The IDE will now download some extra content. Gradle is Android s new package builder which is like make. Once this is done, the main IDE will be shown with the 'Hello World!' project. In the preview pane, you will see a view of what the application is intended to look like on a real smartphone or tablet. This preview pane is only for visualising the layouts you create. It is not an Android Virtual Device (AVD) capable of executing an application. But it is useful as a visualisation of the content_main.xml file which is the file that specifies the intended layout. Notice that you can switch between Design and Text to see either the xml file or its visualisation. 3. ANDROID Emulation To emulate the operation of a real Android device on the PC, Android Studio needs to install an Android Virtual Device (AVD). To make it do this, go to Tools > Android > AVD. When an AVD is being installed, we must select the 'Target' option which specifies the version of Android that our applications will be built for. We must choose an API ( application

COMP61242: Task 2 3 16/04/18 programming interface ) level. Select the API version you wish to install and click install. It is suggested that you install version API version 23. There may already be a suitable AVD shown on the AVD Manager menu display with a tick next to it. To add more API versions, open the Android SDK manager (Tools > Android > Android SDK Manager ). Or click on +Create VirtualDevice at the bottom of the AVD manager screen. A newly installed AVD should be ready for use immediately or after Android Studio has been closed down and reopened (maybe). For this experimental work, it is suggested that you choose AVD device Pixel2 with API version 23. To see the real app in the emulator pane, click on the green arrow in the toolbar, or navigate to the 'Run' menu and click on 'Run'. After a little wait, a dialogue pane called 'Choose Device' will appear. Click on 'Launch emulator' with the appropriate AVD selected. You will need to wait a further few minutes before the app is fully loaded and operational. If you have an Android mobile phone, it may be better to download your apps to that. Once the emulator is running it does not need to be closed. To transfer a different version of your application to the emulator, repeat the process described above without closing the emulator. If you do close the emulator window, you may have to sit and wait while it loads again. If your app does not run automatically on the emulator, the emulated device may be locked as can happen with any smartphone. If this happens, drag the padlock icon up and release it. If this produces your home screen rather than your app, click on the middle icon which is something like a circle with squares dots inside. Then select the icon created for your app. 4. Debugging and Logging While you are using the emulator, Android Studio, will be displaying debug information in a pane. This is 'logcat'. It is Android's way of debugging. You may have previously used print statements to debug Java or C programs. Although you can also use this approach for Android, it is recommended that you use the debugging tools supplied, i.e. LogCat. The statements are shorter to type; e.g. to output a debug message: Log.d(TAG, This is a message );. Note that: 1. Log.d : LogCat supports a few levels of debugging, and each level (or severity ) has its own method (indicated by a single letter): Log.v Verbose Log.d Debug Log.i Information Log.w Warning Log.e Error 2. The TAG argument in Log.d(TAG, This is a message ) is very handy for grouping and filtering messages. When the application is running, a viewing pane should appear at the bottom of the IDE with debugging outputs. It is a good idea to create a filter using the dropdown menu in the logcat panel by selecting 'Edit Filter Configuration' or similar. Then type the package name into the relevant field ( uk.ac.man.cs.comp61242.lab2client). This should then only show debugging information about the app.

COMP61242: Task 2 4 16/04/18 5. The Proxy Server Provided A proxy server lab2-server.py is provided in Python. It is called a proxy server because it will send commands to and receive commands from another client, on behalf of you as a client. The other client may be a real person you want to talk to. But to make experimentation easier, a dummy client called barrybot.py is provided. This will accept any invitation to connect to it, and will then return any messages that are sent to it. To run the proxy server, type 'python lab2-server.py [IP] '. Either specify the IP address of the machine being used, or use the local loop-back (127.0.0.1). The IP address of the laboratory machine being used may be found by typing 'ifconfig'. If no IP address is supplied, then the proxy server defaults to run on the local loop-back IP address (127.0.0.1). The server always uses port 9999. Start barrybot.py after starting the proxy server. The proxy-server responds to or sends the following commands: REGISTER <myusername> - Register myusername with the proxy-server. INVITE <username> - Invite another user to set up a communication channel ACCEPT <username> - Accept username s invitation & forward this message to username DECLINE <username> - Decline username s invitation & forward this message to username MSG <username> <msg> - Send message <msg> to username (after channel established) END <username> - Close channel between me and username & inform username WHO - Get a list of all users who are currently on-line DISCONNECT - Disconnect from the proxy-server DUMP - Requests the proxy-server to dump the internal state on its terminal (for debugging) INFO <msg> - Messages sent to the client by the proxy-server ERROR <msg> - Error messages from the proxy-server Before implementing this protocol in an Android application, you can test it by opening a terminal to act as a client and communicating with barrybot via the proxy-server using TELNET. After opening a terminal, type 'telnet [ip] [port]' to establish a connection with the proxy-server. Use the correct IP address for the proxy-server and specify port 9999. Use the open and send commands and specify an IP address assigned to your machine or another machine. Use the loop back IP address 127.0.0.1 if the proxy-server is implemented on the machine you are using. Once the terminal is connected, anything you type followed by a newline is sent to the proxy-server. Any responses from the proxy-server to you as a client will appear in your TELNET terminal. To terminate the connection to the proxy-server, exit TELNET by pressing <CTRL> + [. You will then drop into the terminal s command mode. Exit the terminal by typing 'quit'. 6. Android Support Software Download the zipped project folder: Lab2Client.zip. Unzip it and take a look at the folders and files within it. You may be surprised at its general structure and the number of files it contains. Then open the folder as a complete project using Android Studio. There are just six files that you need to look at in detail. They all lie within the sub-folder Lab2Client\src\main. The first three are the Java files and the other three are xml files. Here is a brief explanation of what they are:

COMP61242: Task 2 5 16/04/18 MainActivity.java: Resides within \main\java) and contains the java code that runs as the main activity thread for your application and implements its user interface. NetworkConnectionsAndReceiver.java: Resides within \main\java) and contains java code for a worker thread that provides the network connection to the server and keeps a receiver channel open at all times. Transmitter.java: Resides within \main\java) and contains a class that sets up a new shortlived worker thread for each message that is transmitted over the network. res/layout/activity_main.xml: Resides within \main\res\layout) and describes the layout of the screen with buttons, text boxes and other 'widgets' that will be used to provide the application s user interface. You do not have to write the xml code yourself (though you can if you wish) because Android Studio provides a 'Layout Editor' with a 'drag and drop' graphical user interface. You just have to select a widget (for example a button or a text-box) from a menu, and then move it into place, make it the right size, and so on. A very basic layout has been provided with the support software to help you to get started. It has two buttons ( btnkill and btnsendcmd ) and an input box ( cmdinput ). res/values/strings.xml: Resides within \main\res\values) and is a file where string messages are stored for providing text required by the user interface. They are kept together in this one file rather than distributed as 'literal strings' among the many different files of java code. As exemplified by the btnsendcmd button referred to above, the required syntax for accessing string resources is: text="@string/send". AndroidManifest.xml: Resides within \main, and defines some characteristics of your application including its name, permissions needed, SDK version (version of Android studio), etc. 7. The three Java files provided (as listed in the Appendix) 7.1. MainActivity.java : This is the main java class that is run when your app starts. It extends the Activity class and has many predefined methods that listen to events. You do not need to worry about any of these apart from oncreate(). This is the code that runs when the app is opened. Some of this code has already been written for you. You need to write some code here to assign actions to your UI objects. To begin with, you must connect the btnsendcmd button (defined above) so that when it is pressed, it sends the value obtained using the gettext() method of the cmdinput textbox (also defined in activity_main.xml ) to the server using the Transmitter class. Also, the btnkill button defined above must close the app when it is pressed. The code that is needed to connect a button to an action can be found at the end of the oncreate method. 7.2. NetworkConnectionsAndReceiver.java: This class handles the network connection between client and server, and remains active all the time to receive any messages from the network. This class should be run as a worker thread because networking actions should not happen on the main UI thread. The main thread loop constantly listens for commands from the server. When commands are received, they are automatically appended to a textview ( txtserverresponse ) and shown on the Android device. If you are running the python server script on your machine (using 127.0.0.1) you need to set SERVERIP to be 10.0.2.2. This IP address maps the Android emulator to your localhost (127.0.0.1) interface. We must be very careful when passing data between multiple threads. We must use some form of synchronisation to lock reads and writes to avoid race hazards (when threads try to read from and/or write to the same variables at the same time) and deadlocks. In this

COMP61242: Task 2 6 16/04/18 laboratory, we only consider communications between the main thread and a worker thread. We do not consider communications between worker threads. Android has an elegant mechanism for allowing data to be exchanged between the main (UI) thread and other threads. It is provided by a method called 'runonuithread' which is used in this class. When the worker thread wishes to communicate with the user, for example to display a message that has just been received, it simply has to use the runonuithread method to place the required action in the event queue for the UI thread. There may be many runnable events waiting in this queue to be run by the main thread. So the UI thread will deal with these one by one in a way that will not cause any conflicts. When the UI thread is ready to deal with an action placed on the queue by a worker thread, it will do so safely. 7.3. Transmitter.java: This class receives, from the main UI thread, messages that need to be transmitted on the network. Each time such a message arrives from the main UI thread, a new short-lived worker thread is created to transmit it. After that, the worker thread is destroyed. The transmitter thread does not need to use the 'runonuithread' method. 8. Methods of NetworkConnectionsAndReceiver.java 8.1. NetworkConnectionAndReceiver(AppCompatActivity parentref): Class constructor which expects a reference to the UI thread/activity. 8.2. disconnect(): Cleanly disconnects from the server by closing I/O streams and network connection. 8.3. run(): This is the main thread loop that connects to the server and grabs all incoming messages. It should not be directly called. Remember that this is a thread. See the start() method. To change how commands sent to the client are handled, you will need to change the code inside the while loop. 8.4. start(): Since this class extends Thread (Thread java doc), this inherited method causes the thread to start executing. You may need to consult the following documentation on threading: http://docs.oracle.com/javase/7/docs/api/java/lang/thread.html You are allowed, and encouraged, to modify these files as you wish. 9. Getting used to Android Studio Additional documentation is referenced on Blackboard. You may find it useful to watch the You-Tube tutorials suggested, though they are quite long. There are many other tutorials that may be better, and shorter. 10. The sub-tasks for Task 2 Part 2.1 [2 marks] After familiarizing your-self with the IDE and running the sample ( dummy ) project, modify the Hello World message to Hello barrybot. Run the code on the emulator and, if possible, on your own mobile phone. Question 1: Why are literal strings discouraged in Android? What is the preferred alternative?

COMP61242: Task 2 7 16/04/18 Question 2: What is the purpose of the following files and directories created by Gradle: (a) src/main/java, (b) res/ (c) AndroidManifest.xml Question 3: How does the naming of a package affect the file structure of an Android project? Part 2.2 [ 2 marks] Use TELNET to send messages to and from the proxy-server which can be run on a laboratory machine with an IP address that will be provided, or on your own machine using the loop-back address: 127.0.0.1, and port 9999. (May not work on Windows) Check that you can register with the proxy-server and that your name and IP address are stored in the location-server. Question: If barrybot were a real user, how would he know when you have terminated your connection to him? How could the protocol be improved in this respect? Part 2.3 [4 marks] Install and run the Android support software project. It is contained in Lab2Client.zip, but also available as separate java and xml files. Modify the java code to make the btnsendcmd button send the text message REGISTER myname to the server. Also, make the btnkill button close the app when it is pressed. Check that both these actions have the desired effect, and include some logcat debugging statements in your code. Question 1: How did you check that the btnsendcmd and btnkill buttons had the desired effect? Question 2: Explain how you used the logcat debugging facility and show an example of the output obtained (in your demo and your report). Question 3: How does the runonuithread method deal with inter-thread communications in Android? Question 4: Why is runonuithread needed for the NetworkConnectionsAndReceiver thread but not for the Transmitter thread? Part 2.4 [2 marks] Further develop your Android application to enable the registered user to find out who is currently on-line. There will always be a fictitious user online for testing purposes. He just copies messages back when contacted. Display the list obtained on your mobile phone emulator. Question: What happens if you try to contact someone who is not on-line? Part 2.5 [6 marks] Develop and test an Android application for registering, inviting, accepting and setting up a text message link. Demonstrate a two-way message link for interchanging short one-line messages using the MSG command as recognized by the proxy-server. You may choose to do this by one of three methods: (1) communicating with the fictitious user barrybot (who just repeats everything) (2) having two active phones emulated (this may be challenging) (3) working as a partnership with one of your colleagues. Question 1: Which method did you choose, and was it successful?

COMP61242: Task 2 8 16/04/18 Question 2: What are the possible disadvantages of using the proxy-server s MSG command to convey the communications to and from clients, especially if you are thinking about introducing spoken messages and multimedia? Question 3: Are there any deficiencies in the protocol as currently implemented? Part 2.6 [4 marks] Review what you have produced so far, and identify any possible improvements. Implement and test at least one improvement (1, 2 or 4 marks for each improvement: modest, substantial or outstanding). 7. Demonstration & Report You will be asked to demonstrate your achievements with this Task in the laboratory. The demonstration will be worth 20 % of the total mark for Task 2. You must submit a report on Task 2 to Blackboard by the specified deadline (5 pm, Tuesday 1 May 2018). The report must include the code you developed with appropriate documentation. Give details of the development, testing and evaluation in sufficient detail to allow a demonstrator and the external examiner to understand what you have achieved and what you have learned. The report with appropriate code and documentation will be worth 80% of the total mark for Task 2. Document last edited by Barry on 16/04/2018

COMP61242: Task 2 9 16/04/18 Appendix: Support Software MainActivity.java (for Task 2) package com.example.mbassjsp.task2; // Originally created by A Leeming & most recently modified by JSPepper (17-1-2018) // See https://developer.android.com,for android classes, methods, etc // Import classes import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.text.method.scrollingmovementmethod; import android.util.log; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.textview; // Android apps must have a MainActivity class that extends Activity or AppCompatActivity class public class MainActivity extends AppCompatActivity { //Declare class variables: private static final String LOGTAG = "Main UI"; //Logcat messages from UI are identified private NetworkConnectionAndReceiver networkconnectionandreceiver = null; private EditText transmittertext; //Transmitter data variable // Class methods: @Override //Extend the oncreate method, called whenever an activity is started protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // Extend the oncreate method // Set up the view using xml description res>layout>activity_main.xml setcontentview(r.layout.activity_main); Log.i(LOGTAG, "Starting task2 app"); // Report to Logcat // Instantiate the network connection and receiver object networkconnectionandreceiver = new NetworkConnectionAndReceiver(this); networkconnectionandreceiver.start(); // Start socket-receiver thread // Get the receiving text area as defined in the Res dir xml code TextView receivertextarea = findviewbyid(r.id.txtserverresponse); // Make the receiving text area scrollable receivertextarea.setmovementmethod(new ScrollingMovementMethod() ); // Get the kill button as defined in the Res dir xml code Button killbutton = findviewbyid(r.id.btnkill); // Insert kill Button handler & make kill button receptive to being clicked killbutton.setonclicklistener ( new View.OnClickListener() { public void onclick(view v) { // OnClick actions here } } ); // Get the text area for commands to be transmitted as defined in the Res dir xml code transmittertext = (EditText) findviewbyid(r.id.cmdinput); // Get the send button as defined in the Res dir xml code Button sendbutton = findviewbyid(r.id.btnsendcmd); // Insert send-button handler & make send button receptive to being clicked sendbutton.setonclicklistener (new View.OnClickListener()

COMP61242: Task 2 10 16/04/18 // onclick method implementation for the sendbutton object { public void onclick(view v) { // OnClick actions here // Instantiate the transmitter passing the output stream and text to it if ( networkconnectionandreceiver.getstreamout()!= null) { // Check that output stream has been set up Transmitter transmitter = new Transmitter(networkConnectionAndReceiver.getStreamOut(),transmitterText.getText().toString()); transmitter.start(); // Run on its own thread transmittertext.settext(" "); // Clear transmitter text field } // end if clause } } ); } //End of app oncreate method } // End of MainActivity class

COMP61242: Task 2 11 16/04/18 NetworkConnectionAndReceiver.java (for Task 2) package com.example.mbassjsp.task2; // Created by A Leeming & modified JSPepper (17-1-2018) // See https://developer.android.com,for android classes, methods, etc // Snippets: http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example // import classes import android.support.v7.app.appcompatactivity; import android.util.log; import android.widget.textview; import java.io.bufferedreader; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.io.printwriter; import java.net.inetaddress; import java.net.socket; import java.net.unknownhostexception; public class NetworkConnectionAndReceiver extends Thread { //Declare class variables: private Socket socket = null; private static final int SERVERPORT = 9999; // Port that we are connecting to // Channel simulator is 9998 private static final String SERVERIP = "10.0.2.2"; // Host's loopback address private static final String LOGTAG = "Network and receiver"; // For logcat messages private oolean terminated = false; // When FALSE keep thread alive private PrintWriter streamout = null; // Transmitter stream private BufferedReader streamin = null; // Receiver stream private AppCompatActivity parentref; // Reference to main user interface(ui) private TextView receiverdisplay; // Receiver display private String message = null; //Received message //class constructor: public NetworkConnectionAndReceiver(AppCompatActivity parentref) { this.parentref=parentref; } // Get reference to UI // Start new thread method: public void run() { Log.i(LOGTAG,"Running in new thread"); //Create socket and input output streams: try { InetAddress svraddr = InetAddress.getByName(SERVERIP); socket = new Socket(svrAddr, SERVERPORT); //Create socket //Setup i/o streams: streamout = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true); streamin = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException uhe) { Log.e(LOGTAG, "Unknownhost\n" + uhe.getstacktrace().tostring()); } catch (Exception e) { Log.e(LOGTAG, "Socket failed\n" + e.getmessage()); e.printstacktrace(); } // receiver: while(! terminated) // Keep thread running { try { message = streamin.readline(); // Read a line of text from input stream // If the message has text then display it if (message!= null && message!= "") { Log.i(LOGTAG, "MSG recv : " + message); //Get the receiving text area as defined in the Res dir xml code receiverdisplay = parentref.findviewbyid(r.id.txtserverresponse);

COMP61242: Task 2 12 16/04/18 //Run code in run() method on UI thread: parentref.runonuithread(new Runnable() { @Override public void run() { // Display message, and old text in receiving text area receiverdisplay.settext(message + "\n" + receiverdisplay.gettext()); } } ); // end of overrided run method within runonuithread } // end of if clause } catch (Exception e) { Log.e(LOGTAG,"Receiver failed\n" + e.getmessage()); e.printstacktrace(); } } // End of while (! terminated) clause disconnect(); //Call disconnect method to close i/o streams and socket Log.i(LOGTAG,"Thread now closing"); } // End of public void run( ) method public void disconnect() // Method for closing socket and i/o streams { Log.i(LOGTAG, "Closing socket and io streams"); try { streamin.close(); streamout.close();} catch(exception e){/*do nothing*/} try { socket.close(); } catch(exception e) {/*do nothing*/} } // end of disconnect method // Get method for returning the output stream for transmitter to use public PrintWriter getstreamout() {return this.streamout;} // Set method for terminating this thread. Set value to true to close thread. public void closethread(boolean value) {this.terminated = value;} } // End of public class NetworkConnectionAndReceiver

COMP61242: Task 2 13 16/04/18 Transmitter.java (for Task 2) package com.example.mbassjsp.task2; // Created by A Leeming, modified JSPepper (17-1-2018) // See https://developer.android.com,for android classes, methods, etc import android.util.log; import java.io.printwriter; public class Transmitter extends Thread { //Declare class variables: private static final String LOGTAG = "Transmitter"; // Identify logcat messages private PrintWriter printerref = null; // Transmitter output private String transmitterstring = null; // Transmitter input //Class constructor: public Transmitter( PrintWriter printerref, String transmitterstring) { this.printerref=printerref; // Link to network connection output this.transmitterstring=transmitterstring; // Pass text to be transmitted } // end of Transmitter method // Transmit text to output stream in new short lived thread public void run() { Log.i(LOGTAG, "Running in new thread"); //Show as Logcat info try { Log.i(LOGTAG,"Sending command: "+transmitterstring); //Show as Logcat info printerref.println(transmitterstring);} catch (Exception e) //Show as Logcat error { Log.e(LOGTAG, "Failed to transmit\n"+e.getmessage()); e.printstacktrace(); } Log.i(LOGTAG, "Thread now closing"); // Show as Logcat info } // end of run( ) method } // End of Transmitter class strings.xml (for Task 2) <resources> <string name="app_name">task2</string> <string name="hello_world">hello world!</string> <string name="action_settings">settings</string> <string name="send">send</string> <string name="cmd">type Command</string> </resources>

COMP61242: Task 2 14 16/04/18 activity_main.xml (for Task 2) <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.mbassjsp.task2.mainactivity"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignparenttop="true" android:layout_alignparentleft="true" android:weightsum="1"> <TextView android:text="@string/hello_world" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:gravity="top" android:maxlines = "200" android:scrollbars = "vertical" android:id="@+id/txtserverresponse" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/cmd" android:id="@+id/cmdinput" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="left" android:id="@+id/btnkill" android:text="kill" /> <Button android:layout_width="100dp" android:layout_height="wrap_content" android:layout_gravity="right" android:id="@+id/btnsendcmd" android:text="@string/send" /> </LinearLayout> </LinearLayout> </RelativeLayout>

COMP61242: Task 2 15 16/04/18 AndroidManifest.xml (for Task 2) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mbassjsp.task2"> <uses-permission android:name="android.permission.internet" /> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundicon="@mipmap/ic_launcher_round" android:supportsrtl="true" android:theme="@style/apptheme"> <activity android:name=".mainactivity"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Task 2 Support Software Documentation (Jeff Pepper 16 Feb 2018) The main activity thread (sometimes called UI thread) creates objects for displaying text, entering text, and a button listener (Send button). When the app is launched the UI thread is executed. From the UI thread, the 'socketandreceiver' object is created. Then the UI thread starts a 'socketandreceiver' thread. In the 'socketandreceiver' thread a socket is created with the correct IP address and port number. Then, in a continuous loop, the input stream of the socket is read using a readline method (which is a blocking method) and waits for a "\n" linefeed character. On receiving a "\n" character, a new runnable object is created with the object's own run method defined. We then use the 'runonuithread' method to pass the runnable object to the event queue of the UI thread. When the UI thread services this event it will execute the object's run method. In our case it will display the received message in the text display area of the user interface. On a Send button being clicked the UI thread creates a transmitter object. The text entered by the user is grabbed and passed to the constructor of the transmitter object. Then the UI thread starts a transmitter thread by invoking the run method of the transmitter via the start method. The transmitter thread runs the write method for the socket stream and transmits the message. The transmitter thread then "dies". This all gets repeated on the next Send button click. This android project was built from an "Empty Activity" using API 15. To start Android Studio from a lab machine type: "start_android_studio.sh 61242"