Limited Offer Get 25% off — use code BESTW25
No AI No Plagiarism On-Time Delivery Free Revisions
Claim Now

COMP28512: Mobile Systems

COMP28512: Task 4 1 9/03/20
University of Manchester
School of Computer Science
COMP28512: Mobile Systems
Semester 2: 2020
Laboratory Task 4
Messaging with Android Smartphones
1. Introduction
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 4 is concerned with introductory material and Task 5 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.
Barry
Location
server
Proxy
Server
Register,
Invite,
Accept,
Ack etc.
Register,
Invite,
Accept,
Ack etc.
Invite, Accept
Proxy
Server
Ack, etc.
Channel
simulator
Jeff
COMP28512: Task 4 2 9/03/20
Rather than setting up a peer-to-peer link for direct message and speech communication, you
will eventually (in Task 5) 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 biterrors. Worse still, there may be security attacks and eavesdroppers trying to intercept and
disrupt the communication. Do not worry about this in Task 4, and keep things simple by
using the ‘MSG’ command to send messages (see the list of Proxy Server commands later).
2. The Proxy-Server Provided
A proxy server ‘lab4-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. BarryBot 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 lab4-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 link with you.
ACCEPT <username> – Accept username’s invitation and inform the user.
DECLINE <username> – Decline username’s invitation and inform the user.
MSG <username> <msg> – Send message <msg> to username (after link is established)
END <username> – Close the link 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
3. Android Development
You will need to become familiar with Android development and simulation facilities. There
are many options for Linux, Windows and MAC users. This task concentrates on the use of
Android Studio in Linux. All the necessary software is open-source.
3.1. Android Studio
Android Studio is the ‘integrated development environment’ (IDE) made available by Google
for developing Android applications. It 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.
Android Studio is available on the Tootill laboratory machines it may be downloaded from
https://developer.android.com/studio and installed on your own computer at home. Extensive
documentation may also be found on this web-site starting at
https://developer.android.com/studio/intro.
COMP28512: Task 4 3 9/03/20
3.2. Running Android Studio for the first time
To start Android Studio on a University machine type “start_android_studio.sh 28512”. When
you do this for the first time you see a window with about 5 options including ‘Start a new
Android Project’. Or you may have to select the ‘file’ tab and close a project that Android
opened automatically for you. Select ‘Start a new Android Project’ and choose an application
name such as ‘My Application’ and a short company domain name like ‘Barry.com’. Notice
that Android Studio creates a ‘package name’ based on your choices. On the subsequent
pages, accept the default target devices, select ‘Empty Activity’ (which specifies a very simple
‘Hello World’ project) and accept the default ‘customize’ activity and layout names. Click on
‘finish’, then take a look at the IDE screen view. It is explained in the
https://developer.android.com/studio/intro page. Referring to figure 3 in this introduction,
notice the toolbar (1), the navigation bar (2) and the edit window (3). Notice also the vertical
tool window bar (4) which controls how the space on the right hand side of the IDE view may
be used to display various other types of windows (5). Observe that the project name ‘My
Application’ appears above the left-hand window and that there is a pull-down menu below it.
Among the pull-down menu options is ‘Android’ and ‘Project’, Initially select ‘project’ to view
the ‘Project Window’. You may find it useful to watch the ‘YouTube’ tutorial:
https://www.youtube.com/watch?v=-igAiudpBng The official guide is also helpful:
https://developer.android.com/guide??
The process of creating the first new project sets up a new folder which may be called
‘AndroidStudioProjects’. On University machines, this will be created in your own working
directory. If your first new project is called ‘MyApplication’, it is represented by a folder called
‘MyApplication’ within the ‘AndroidStudioProjects’ folder. If you expand the ‘MyApplication’
folder as seen in the left-hand Project window, you will see that it contains many sub-folders
and files. Expand the ‘app’ sub-folder, the ‘src’ folder within it and finally the ‘main’ folder.
Now you see a folder called ‘java’, a folder called ‘res’ and a file called AndroidManifest.xml.
Within the ‘java’ folder is a ‘package’ whose name was mentioned earlier. Within the ‘res’
folder (resources) are several sub-folders which include ‘layout’ and ‘values’. We can now
find the files that are at the heart of the MyApplication project. They are:
(i) MainActivity.java within a ‘package’ sub-folder of the folder called ‘java’.
(ii) activity_main.xml in the sub-folder called ‘res/layout’
(iii) strings.xml in the sub-folder called ‘res/values’
(iv) AndroidManifest.xml in the sub-folder ‘main’.
‘MainActivity.java’ contains the java code that is run when the application starts. It extends the
‘AppCompatActivity’ class and has many predefined methods. These methods include
‘onCreate()’ that runs when the app is opened.
‘activity_main.xml’ contains xml code that describes the layout of the smart-phone screen with
buttons, text boxes and other GUI ‘components’ that will be used to construct the application’s
user interface (UI).
‘strings.xml’ is a file where string messages are stored for providing text required by the user
interface. They are kept together in this one file. This is better than placing your literal strings
messages within your java or xml code.
‘AndroidManifest.xml’ contains xml code that defines some characteristics of your application
including its name, permissions needed and the SDK version (version of Android studio).
Very basic versions of each of the four files mentioned above are written automatically for you
when you create your first new ‘empty activity’ project. Together they form an executable
COMP28512: Task 4 4 9/03/20
project called the ‘Hello World’ project. Many other folders and files are also created within
the project folder, and when you have successfully built the application, an ‘Android
Application’ (APK) file will be created, ready to be downloaded to an emulated or real mobile
device.
In Android Studio, the edit-window (3) can be made to display the contents of
‘MainActivity.java’ by clicking on the appropriate tab in the navigation bar (2). Clicking on the
‘activity_main.xml’ tab in the navigation bar (2) causes the edit window to display the contents
of the ‘activity_main.xml’ file and there are several ways of doing this. If you select ‘text’ form,
you will see the xml code that defines the layout of the smartphone screen. If you select
‘design’ form, you will see a ‘preview pane’ with a visual representation of the screen layout
corresponding to the xml code. There are three ways of viewing this visual representation: as
a ‘design surface’, a ‘blueprint surface’ or a combination of these two types of display. You
can switch between these three options by clicking on a ‘Select Design Surface’ tab above the
preview pane. The xml code for ‘strings.xml’ and the xml code for ‘AndroidManifest.xml’ can
similarly be placed in the edit-window by clicking on the appropriate tabs.
Creating and building the first new project as described above also sets up the Android Studio
environment with the required software links, for example to the SDK (Software Development
Kit). The new project may be ‘built’ to produce an application (app) that may be run on a
mobile phone or an emulator. To do this, click on the ‘build’ tab, and you will see “Gradle
Build Running” at the bottom of the window. Gradle is Android’s package builder which is like
‘make’. The IDE will download some extra content and complete the ‘build’ process. Once
this is done, the ‘MyApplication’ project folder will be augmented to contain all the information
needed for running the ‘Hello World’ application on an Android smart-phone.
The ‘preview pane’ is only for visualising the GUI (graphical user interface) layouts you create.
It is not capable of executing an application. You can always switch between ‘Design’ and
‘Text’ to see either the visualisation or the corresponding xml file in text form. When designing
GUI screens for smartphone applications, 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 GUI component (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.
To run an application, such as the ‘Hello World’ application created above, you can use
Emulation using an ‘Android Virtual Device’ (AVD) as described in the next section, or you can
connect a real smartphone or tablet to the PC using a USB connector and download the
application to it.
3.3 Code for ‘Hello World’ application
The contents of the files at the heart of the ‘Hello World’ application, as created automatically
by Android Studio, are listed below.
MainActivity.java:
package com. barry.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState)
COMP28512: Task 4 5 9/03/20
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

activity_main.xml:
<?xml version=”1.0″ encoding=”utf-8″?>
<android.support.constraint.ConstraintLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:app=”http://schemas.android.com/apk/res-auto”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”com.barry.myapplication.MainActivity”>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Hello World!”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintLeft_toLeftOf=”parent”
app:layout_constraintRight_toRightOf=”parent”
app:layout_constraintTop_toTopOf=”parent” />
</android.support.constraint.ConstraintLayout>
strings.xml:
<resources>
<string name=”app_name”>My Application</string>
</resources>
AndroidManifest.xml:
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”barry.myapplication”>
<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>
The MainActivity.java file listed above specifies the package name, imports the necessary
libraries (selected automatically), and declares the MainActivity class which inherits from
AppcompatActivity. The inherited version of the onCreate() method is over-rided by a new
version which will be executed straight-away when the application is started. The
‘super.onCreate(..) statement makes sure that the original version of onCreate() is included
COMP28512: Task 4 6 9/03/20
within the over-rided version. The ‘setContentView’ statement specifies that activity_main.xml
as discussed below is used to specify the initial screen layout. ‘R’ refers to the ‘res’ file within
‘main’.
The activity_main.xml file listed above specifies where GUI components (e.g. buttons and
text-boxes) will be placed on a smartphone screen. There are different ways of doing this
including the ‘constraint layout’ method. Other ways exist. With ‘constraint layout’’ all the GUI
components are placed within an area called the ‘ConstraintLayout’ specified on line 2. Some
xml namespaces (xmlns) are defined to allow names like layout_width, layout_height and text
to be uniquely associated with a ‘uniform resource identifier’ (URI) such as ‘android’. Two
other URIs are ‘app’ and ‘tools’. In the version of activity_main.xml listed above, the
layout_width and layout_height of the ConstraintLayout area are defined in lines 6 and 7 to be
the dimensions its ’parent’ which is the full smartphone screen. A ‘text-view’ box is then
created (by lines 9 to 16) within the ConstraintLayout, and the width and height of this box are
defined as ‘wrap content’ which means that they will vary according to the message that the
text-view box is required to display. In this case the message is ‘Hello World’. The
dimensions of the text-view box and its position are defined with reference to the ‘parent’, (the
screen), by the four ‘app:layoutconstraint’ statements. These four statements make the
maximum dimensions of the text-view box identical to those of the full screen. The actual
dimensions of the text-view box will change as different messages are displayed.
The details of ‘strings.xml’ and ‘AndroidManifest.xml’ need not be mentioned at this stage.
The syntax for accessing string resources that are within the string.xml file is:
text=”@string/send”.
3.4 Writing your own first application
3.4.1 The screen layout
As an example of a screen layout, the one given by the Hello World project is not very helpful.
But we can modify it to make it more interesting and useful. Start another new project by
proceeding as for ‘Hello World’ and selecting a new project name such as MyApplication1.
Again ‘Empty Activity’ must be selected. Modify the project to create the new screen layout
sketched below. Start with a pen and paper sketch of the layout that you have in mind. The
new screen layout has a TextView box as before. But it also has an ‘EditText’ (text-input) box,
and two labelled bush-buttons. You could design this layout yourself using the Layout Editor
to select GUI components (buttons and text-boxes) from a menu and move them into place.
However, we have provided a version of activity_main.xml that produces the required layout.
Replace the activity_main.xml file for the ‘Hello World’ layout by the new one to produce a
screen which corresponds to the sketch. Have a look at the ‘text view’ and also the ‘design
view’ of the xml file to become familiar with their construction. Notice that each component is
given a unique identification (ID) name. Instead of “Hello World” we have a new message
“TextViewBox” which is read from resvaluesstrings.xml. Also, the text-view box has been
made to scroll so that it can show multiple messages, one after the other. There are many
alternative ways of writing this xml code.. You can run the new project straight-away, but to
make the new GUI components do something useful, you must modify the java code in
‘MainActivity.java’.
COMP28512: Task 4 7 9/03/20
Sketch of a new layout
activity_main.xml for the new layout
<?xml version=”1.0″ encoding=”utf-8″?>
<android.support.constraint.ConstraintLayout
xmlns:android=http://schemas.android.com/apk/res/android
xmlns:app=http://schemas.android.com/apk/res-auto
xmlns:tools=http://schemas.android.com/tools
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”.MainActivity”>
<TextView
android:id=”@+id/myTextViewBox”
android:layout_width=”800px”
android:layout_height=”300px”
android:background=”#00BCD4″
android:text=”@string/textView”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintRight_toRightOf=”parent”
app:layout_constraintLeft_toLeftOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.12″ />
<EditText
android:id=”@+id/myEditTextBox”
android:layout_width=”800px”
android:layout_height=”120px”
android:background=”#8BC34A”
android:hint=”@string/editText”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintRight_toRightOf=”parent”
app:layout_constraintLeft_toLeftOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.33″ />
<Button
MyApplication1
Text ViewBox
Edit Text box
Send
button
Kill
button

COMP28512: Task 4
android:id=”@+id/myKillBtn”
8 9/03/20

android:layout_width=”200px”
android:layout_height=”120px”
android:text=”@string/kill”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintLeft_toLeftOf=”parent”
app:layout_constraintHorizontal_bias=”0.3″
app:layout_constraintRight_toRightOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.42″
android:onClick=”killMethod” />
<Button
android:id=”@+id/mySendBtn”
android:layout_width=”200px”
android:layout_height=”120px”
android:text=”@string/send”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintHorizontal_bias=”0.7″
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent”
app:layout_constraintVertical_bias=”0.42″
android:onClick=”sendMethod”/>
</android.support.constraint.ConstraintLayout>
This version of activity_main.xml is written specifically for the ‘pixel 2’’ smartphone whose
screen has 1080 by 1920 pixels. Referring directly to pixels (px) rather than pds is not
recommended and generates a warning. It is better to use ‘density independent pixels’ (dp or
dip) which are based on the density of pixels on the screen. A further alternative is to use
scaled independent pixels (sp) which are the same as dp but are scaled by the user’s font
size preference. You may need to adapt component sizes given in px to the screen size of
your own phone. Or you could make this happen automatically by using ‘dp’ units.
Notice how setting a constraintHorizontal_bias and a constraintVertical_bias can be used to
move buttons and text boxes up and down the screen. The bias must lie between “0.0” and
“1.0”. By default it is “0.5” which centres the component within its horizontal or vertical
constraints. Reducing the horizontal bias towards “0.0” moves the component to the left.
Reducing the vertical bias towards “0.0” moves the component up.
Notice that each button has its own ID name (‘mySendBtn’ and ‘myKillBtn’) and that we have
included the name of an ”onClick’ method (‘killMethod’ and ‘sendMethod’) within the code for
each button. This is optional, but it is a simple way of specifying which java code (normally
within mainActivity.java) is to be run when a button is clicked. The ‘onClick’ methods are often
referred to as ‘call-back’ methods. If you do not provide these call-back methods, nothing will
happen when you click on a button.
Text-edit and text-view boxes do not have call-back methods but they need ID names
(‘myTextViewBox’ and ‘myEditTextBox’) to allow java code within mainActivity.java to identify
them and read text from them or write text to them. Notice how the background colour
“#8BC34A” is specified in red/green/blue form for the text-view box. You can do this for the other
components if you wish.
[Question: What is the difference between “start of” and “top of”?]
COMP28512: Task 4 9 9/03/20
3.4.2 Code for Activity.java
We now have a screen layout with useful components. Let’s make them do the following.
(1) Allow the user to enter a message in the ‘text-edit’ box
(2) Transfer the message to the ‘text-view’ box when the ‘send’ button is pressed .
(3) Make the text-view box ‘scroll’ so that previous messages are moved up.
(4) Perform a ‘system reset’ when the ‘kill’ button is pressed.
Before starting to write any java code, activate ‘automatic imports’ by finding the ‘Auto
Imports’ menu which is under ‘file>settings>Editor…’, >’default settings’ or ‘permissions’.
Select ‘Optimise imports on the fly’ and ‘Add unambiguous imports on the fly’. ‘On the fly’
really means ‘automatically’.
The following java code will find and activate the TextView box that was defined by the xml
code above, because we gave it the id ‘myTextViewBox’. We have given it the same name
‘myTextViewBox’ as an object within our java code. We then make it scrollable and display
messages:
TextView myTextViewBox = (TextView)findViewById(R.id.myTextViewBox);
myTextViewBox.setMovementMethod(new ScrollingMovementMethod() );
myTextViewBox.setText(“Any message”);
myTextViewBox.setText(“Any other message”);
The following java code will find and activate the EditText box with id ‘myEditTextBox’. It is
given the java object name ‘myEditTextBox’. The second line reads the message from this
box that has been entered by a user. It is read as a String called myText. The third line
sends myText to be displayed by ‘myTextViewBox’.
EditText myEditTextBox = (EditText)findViewById(R.id.myEditTextBox);
String myText = myEditTextBox.getText( ).toString( );
myTextViewBox.setText(myText);
The following java code provides a call-back method for the Button with id ‘mySendBtn’ . We
no longer need to use ‘findViewById’ because the xml code for this button includes the
statement ‘android:onClick=”sendMethod”. This defines the name of a call-back method that
must be provided by our java code. We could use’findViewById’ to link to the button as with
the EditText and TextView boxes. But it is probably easier to use the code below. We just
have to define a public method with the name ‘sendMethod’ (as specified in the xml code).
When the button is pressed, the call-back method is executed automatically. It sends the
message “Send button pressed” to myTextViewBox and clears myTextEditBox.
public void sendMethod(View v)
myTextViewBox.setText(“Send button pressed”);
myTextEditBox.setText(” “); // Clear TextEditBox
Using the three items of java code listed above within the onCreate method of
mainActivity.java will allow you to carry out Experiment 4.1.
3.5 Second application
Now, consider the problem of sending messages to the proxy-server, receiving any messages
that the proxy server sends back at any time, displaying these messages to the user and
acting on them. Install the following two java files into the project:
(1) NetworkConnectionsAndReceiver.java
(2) Transmitter.java
COMP28512: Task 4 10 9/03/20
These must be made to run as separate threads. You do not have to modify these files, but
you must understand what they do.
The NetworkConnectionsAndReceiver.java thread requires a method called messageHandler
which is not run on the NetworkConnectionsAndReceiver thread. Instead it is placed on the
event queue to be run on the mainActivity (UI) thread. You need to write the code for this
method and place it within the mainActivity class. Much of the java code you need to write
for Experiment 4.2 can be placed within this method.
3.6. ANDROID Emulation
For emulation, ‘Android Studio’ can install an ‘Android Virtual Device’ (AVD). To make it do this,
go to Tools > Android > AVD. Select a ‘Target’ option to select an API level which is the
version of Android to be used by the AVD. API stands for ‘application programming interface’
level. Install version API version 23. This may already be shown on the ‘AVD Manager’ menu
with a tick next to it. Otherwise, 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). Choose AVD device ‘Pixel 2’ with API version 23.
To see the 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 an appropriate AVD selected. You will then need to
wait a further few minutes before the app is fully loaded and operational.
Once the emulator is running, it should not be closed. If you do close it, you may have to wait
while it loads again. The emulated device can become locked as with a real smartphone. You
can unlock it in the obvious way. To find your app from the ‘home screen’, click on the Apps
folder icon.
Installing and running an AVD on your own lap-top computer as described above is normally
straightforward and not too slow. However, this process can be very slow on University
machines. The School has therefore devised an alternative way of launching the AVD which
is much faster. To launch the alternative (faster loading) AVD configuration on a Tootill
machine, open a new terminal and type ‘start_fast_avd_android.sh 28512’.
3.7. Running your application on a real smartphone or tablet.
To run your application on an Android phone or Tablet, connect it to a PC by a USB cable.
Then you have to enable ‘Developer Options’ on your mobile device. The way to do this is
not very obvious and you may have to look up the details for your particular device online.
Android Studio gives some useful information in the ‘Connect Assistant’ window (on right).
For a Samsung mobile phone and Tablet it was necessary to select:
– Settings
– About device
– Software information
– Build number
Tap ‘Build Number’ 7 times to cause a new tab, labelled ‘Developer Options’, to appear in the
previous screen. Select this new tab and a long list of new options will be given. Among
these options is ‘Allow USB debugging’ which should now be selected. Authorize the USB
connection on your device using the pop-up window that appears. You may have to answer
‘yes’ to a question that pops up.
COMP28512: Task 4 11 9/03/20
You can now download an App from Android Studio by clicking ‘Run’. You should see the
name of your mobile device in the ‘Connected Devices’ list. Select it and click OK. The
application will then be built and downloaded to your device, with an appropriate icon. Make
sure that you are not using a USB cable that is only for charging.
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 may any string message you choose, such as:
TAG = “Activity Manager”
TAG is useful for indicating which part of your code generates a ‘logcat’ message, and
Android Studio provides ways of grouping messages together and filtering out messages you
do not want to see. When the application is running, a viewing pane should appear at the
bottom of the IDE with debugging outputs. Filters may be created using the dropdown menu
in the logcat panel by selecting ‘Edit Filter Configuration’ or similar. It is a good idea to type
the package name into the relevant field (e.g. uk.ac.man.cs.XXX), so that only debugging
information about the app itself will be displayed. If you wanted to concentrate on socket
errors, for example, you could type “socket” into the relevant field.
5. Android Support-Software for interaction with Proxy-Server
For Experiment 4.2, you need to develop an Android project that is able to do three actions:
(1) interact with a user, (2) receive any transmissions from the proxy-server, (3) send
transmissions to the proxy-server. To help you, we provide support-software which sets up a
socket for listening to messages received from the proxy-server and for transmitting textmessages to the proxy-server. This support-software is provided in source form as a fragment
of java code and two java files: NetworkConnectionsAndReceiver.java and Transmitter.java’.
These are listed in the Appendix.
Before modifying your project to include this support software, make a copy of your previous
project so that you can demonstrate it.
Now introduce the support-software into your project as follows:
Java code fragment for messageHandler. This must be placed within the MainActivity.java
code that is run when the app starts. Use the IDE editor (with cut and paste) to do this.
COMP28512: Task 4 12 9/03/20
NetworkConnectionsAndReceiver.java must be placed alongside MainActivity.java within the
same package, within the ‘java’ folder. It 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 must also be placed in the same package. It contains a class for setting up
a worker-thread for transmitting a message over the network. This worker-thread will not
remain open at all times. The java code sets up a new short-lived worker-thread for each
message and kills the thread when the message has been transmitted.
To place the two new java files alongside ‘MainActivity.java’, highlight or expand the
appropriate package in the Project Window and copy them over from your PC.
6. More details of three Java files
6.1. MainActivity.java
This is the main java class that includes the method onCreate() which is run when your app
starts. When a project has more than one thread running simultaneously, this code is often
run as the ‘main thread’ also referred to as the ‘UI thread’. This thread is normally
responsible for interactions with the user using text-boxes, buttons and other widgets. It
extends the ‘AppCompatActivity’ class and has many pre-defined methods that listen to
events. You do not need to worry about any of these apart from ‘onCreate()’. You need to
write some code here to assign actions to the UI components (text boxes, buttons, etc.) that
were introduced into ‘activity_main.xml’ as described in Section 3.4.1 You will need to
activate the TextView and EditText boxes and provide call-back methods for the ‘Send’ and
‘Kill’ buttons. The ‘Kill’ button must be made to close the app by executing: “System.exit(0);”
when it is pressed.
6.2. NetworkConnectionsAndReceiver.java:
This class handles the network connection between the Android app and the proxy-server. It
remains active all the time. This class is run as a worker-thread because networking actions
should not happen on the main (UI) thread. The worker-thread constantly listens for
messages from the server.
When a project has more than one thread, as in Expt 4.2, some form of synchronization must
be used to avoid race hazards (when threads try to read from and/or write to the same
variables at the same time) and deadlocks. Such conflicts could occur if the main (UI) thread
and a worker-thread are trying to write to a text-view box at the same time. Android has a
mechanism for avoiding conflicts between the main (UI) thread and other threads. It is
provided by a method called ‘runOnUiThread’. When a 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 main
(UI) thread. There may be many runnable events in this queue, waiting to be run by the main
(UI) thread. So the main (UI) thread will deal with these runnable events one by one in a way
that will not cause any conflicts. To find out more about threads and threading, consult the
following documentation:
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
The NetworkConnectionsAndReceiver.java class has the following methods:
1. NetworkConnectionAndReceiver ( AppCompatActivity parentRef ): Class constructor
which expects a reference to the UI thread/activity.
COMP28512: Task 4 13 9/03/20
2. disconnect(): Cleanly disconnects from the server by closing I/O streams and the
network connection.
3. run(): This is the main thread loop that connects to the server and grabs all incoming
messages. It should not be called directly. To change how commands sent to the
client, are handled, you will need to change the code inside the while loop.
4. start(): This inherited method causes the thread to start executing.
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
6.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 class does not need to use the ‘runOnUiThread’ method.
7. Further Explanation of the Task 4 Support Software
The main activity thread is sometimes called the User Interface (UI) thread. When an app is
launched, the onCreate() method of mainActivity.java (the UI thread) is executed. This
onCreate() method creates the ‘NetworkConnectionsAndReceiver’ object, and this is used to
start a ‘NetworkConnectionsAndReceiver’ thread which remains active all the time.
In the ‘NetworkConnectionsAndReceiver’ 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, the thread creates a new runnable object with the object’s own
run method defined. It then uses 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. If a socket cannot be created, for example because the proxy-server is not
on-line, a ‘logcat’ message “Socket error” will be generated.
When the Send button is 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 when the Send button is
clicked again.
8. The Experiments for Task 4
Expt 4.1 Talking to yourself
Before starting this experiment, create and run the ‘Hello world’ project on the emulator and a
real device. Then create a layout as shown and described in Section 3.4.1 and activate the
UI components as described in Section 3.4.2. Run this first application on an emulator and a
real mobile phone or tablet. The device will be just ‘talking to itself’ at this stage. Save the
application so that you can demonstrate it later. Take a screenshot of it by clicking the camera
button on the side bar of emulator. The screenshot will be automatically saved on your
desktop.

COMP28512: Task 4
Questions we may ask you:
14 9/03/20

1. What is the purpose of the following files and directories created by Gradle?:
(a) src/main/java. (b) res/ (c) AndroidManifest.xml
2. Why are literal strings discouraged in Android? What is the preferred alternative?
3. How did you use logcat to debug your software?
4. What is a ‘call-back Method?
5. Do all the UI components work correctly?
6. Which emulator and which real device did you use?
Expt 4.2 Talking to the Server
Download ‘server.py’, ‘barryBot.py’, ‘NetworkConnectionsAndReceiver.java’ and
‘Transmitter.java’ from BlackBoard. Run the proxy server ‘server.py’ and the dummy client
‘BarryBot.py’ in separate terminal windows. Modify the project you created in Expt 4.1 by
adding the two new java files into the same folder as ‘MainActivity’, as explained in Section 5.
Add the ‘message handler’ method to your existing java code in MainActivity. You may need
to modify the AndroidManifest.xml file by including:
<uses-permission android:name=”android.permission.INTERNET” />
before <application> to give permission to have a network connection.
At the beginning of OnCreate() in ‘MainActivity’, add a networkConnectionAndReceiver object
as follows:
// Instantiate the network connection and receiver object
networkConnectionAndReceiver = new NetworkConnectionAndReceiver(this);
networkConnectionAndReceiver.start(); // Start socket-receiver thread
Then modifiy the ‘sendMethod’ call-back method to send messages extracted from
myEditTextBox to the server when ‘mySendBtn’ is clicked. Do this by creating a new
transmitter object as follows:
Transmitter transmitter = new Transmitter(networkConnectionAndReceiver.getStreamOut(),
transmitterText);
transmitter.start(); // Run on its own thread
Then, run your application. Enter the text-message “Hello BarryBot” and send it to the server.
Check that the message is received by the server by observing the server’s terminal window.
The server will reply with the message “Error Not a command”. This message should be
displayed in myTextViewBox. You will now know whether you are communicating
successfully with the server.
Send each following commands to the server and observe what replies you receive.
1. ‘REGISTER Myname’
2. ‘WHO’
3. ‘INVITE BarryBot’
4. ‘MSG BarryBot Hello BarryBot’
5. ‘END BarryBot’
6. ‘DISCONNECT’
Questions
1. What is multi-threading and how is it done?
2. Why does this application have to be multi-threaded?
3. How does the ‘runOnUiThread’ method deal with inter-thread communications in Android?
COMP28512: Task 4 15 9/03/20
4. Why is ‘runOnUiThread’ needed for the NetworkConnectionsAndReceiver thread but not
for the Transmitter thread?(Otherwise the two thread might try to write this text box at the
same time)
Expt 4.3: A smarter application
You can already have a text conversation (a ‘chat’) with BarryBot but it inconvenient to have
to type the Sip messages (Register etc) yourself. Therefore create a new EditText box to
allow the user to enter a name and create a ‘Register’ button for registering this name
automatically with the server. Create further UI components for ‘WHO’ and ‘INVITE’. Then
create an interface for exchanging messages conveniently between the registered name and
the invited name. Your application should be able to accept, reject and end conversations.
Demonstrate a two-way message link for interchanging short one-line messages with
BarryBot using the proxy-server.
Questions:
1. What are the main features of your new layout and how do they work?
2. How can you test somebody calling you?
3. What happens if you try to register with a name that is already in use?
4. Why do you need to disconnect yourself when exit? If you don’t, what happens?
5. 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?
Expt 4.4: A few extras maybe
Once you get a new message, it would be nice to receive a notification by sound (a tone or a
buzz). To allow this, you need to give ‘vibrate’ permission adding the following statement to
the ‘AndroidManifest.xml’ file:
<uses-permission android:name=”android.permission.VIBRATE” />
Then modify your java code in MainActivity by adding
Vibrator vibrator= (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
vibrator.vibrate(200); //200 milliseconds are the length of vibration
For setting a ringtone, add
//add notification ring
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone rt = RingtoneManager.getRingtone(context, uri);
rt.play();
It will be necessary to import the relevant library package.
Expt 4.5: Review and finalise
Review what you have produced and identify any problems and possible improvements.
Adjust and finalise layout and the positions and sizes of UI components. Maybe add a
background and a margin. You could use various widgets to make your current design more
user-friendly such as a ‘spinner’ for selecting the target user. To find out how to use a spinner,
see: https://developer.android.com/guide/topics/ui/controls/spinner#java.
For more information, see: https://developer.android.com/guide
COMP28512: Task 4 16 9/03/20
7. Demonstration
You will be asked to demonstrate your achievements with this Task in the laboratory. No
report required. The mark for Task 4 will be based on your demonstration only. You will be
expected to demonstrate your application and give details of its development, testing and
evaluation. This should allow an assessor and the external examiner to understand what you
have achieved and how much you have learned.
Document last edited by Yueer on 23/7/19 & Barry on 3/3/20
Task 4 Support Software
messageHandler Method in main activity
public static void messageHandler()
// Display message, and previous text in the receiving text area
String currentText = displayText.getText().toString();
displayText.setText(“==>” + NetworkConnectionAndReceiver.message + “n” + currentText);
NetworkConnectionAndReceiver.java
package com.example.myapplication; //replace this with your own package name
public class NetworkConnectionAndReceiver extends Thread
//Declare class variables
private Socket socket = null;
private static final int SERVERPORT = 9999; // Port we are connecting to
private static final String SERVERIP = “10.0.2.2”; // Host’s loopback address
private boolean terminated = false; // When FALSE, keep thread alive & polling
private PrintWriter streamOut = null; // Transmitter stream
private BufferedReader streamIn = null; // Receiver stream
private AppCompatActivity parentRef; // Reference to main UI
public static 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()
//Create socket and input output streams
try //Create socket
InetAddress svrAddr = InetAddress.getByName(SERVERIP);
socket = new Socket(svrAddr, SERVERPORT);
//Setup i/o streams
streamOut = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
catch (UnknownHostException uhe) terminated = true;
catch (Exception e) e.printStackTrace(); terminated = true;
//receiver
while(!terminated) // Keep thread running
try message = streamIn.readLine(); // Read line of text from input stream
COMP28512: Task 4 17 9/03/20
// If message has text then display it
if (message != null && message != “”)
//Run code in run() method on UI thread
parentRef.runOnUiThread(new Runnable()
@Override public void run()
MainActivity.messageHandler();
);

catch (Exception e) e.printStackTrace();

//Call disconnect method to close i/o streams and socket
disconnect();

// Method for closing socket and i/o streams
public void disconnect()
try streamIn.close(); streamOut.close();
catch(Exception e) /*do nothing*/
try socket.close(); catch(Exception e) /*do nothing*/
this.terminated = true;

// Getter method for returning the output stream for the transmitter to use
public PrintWriter getStreamOut() return this.streamOut;

Transmitter.java
package com.example.myapplication; //replace this with your own package name
public class Transmitter extends Thread
//Declare class variables
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
// Transmit text to output stream in new short lived thread
public void run() try printerRef.println(transmitterString); // Transmit text
catch (Exception e) e.printStackTrace();

The post COMP28512: Mobile Systems appeared first on My Assignment Online.

Plagiarism Free Assignment Help

Expert Help With This Assignment — On Your Terms

Native UK, USA & Australia writers Deadline from 3 hours 100% Plagiarism-Free — Turnitin included Unlimited free revisions Free to submit — compare quotes
Scroll to Top