0% found this document useful (0 votes)
26 views91 pages

MC Lab Manual

The document is a lab manual for the Mobile Computing course (CSC 603) for TE Computer Engineering students during the academic year 2024-2025. It outlines the vision and mission of the Computer Department, program outcomes, lab outcomes, recommended software, and a list of practical experiments to be conducted. Additionally, it includes a sample experiment on implementing a Bluetooth network for file transfer, along with relevant code snippets for Android application development.

Uploaded by

x0598233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views91 pages

MC Lab Manual

The document is a lab manual for the Mobile Computing course (CSC 603) for TE Computer Engineering students during the academic year 2024-2025. It outlines the vision and mission of the Computer Department, program outcomes, lab outcomes, recommended software, and a list of practical experiments to be conducted. Additionally, it includes a sample experiment on implementing a Bluetooth network for file transfer, along with relevant code snippets for Android application development.

Uploaded by

x0598233
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

LAB MANUAL

Course Name : Mobile Computing

Course Code : CSC 603

Lab Code : CSL 603

Class : TE Computer Engineering

Semester : VI

Div : A & B

Academic Year : 2024-2025 (REV- ‘C’ Scheme)

Prof. Tulsidas R. Mane Dr. Rais Mulla

Subject In-charge ( HOD of Computer Department)

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Vision of Computer Department
To develop a centre of excellence in computer engineering and produce globally competent engineers
who contribute towards the progress of the engineering community and society as a whole.

Mission of Computer Department

 To provide students with diversified engineering knowledge to work in a multidisciplinary


environment.
 To provide a platform to cultivate research, innovations and entrepreneurial skills.
 To produce world-class computer engineering professionals with moral values and leadership
abilities for the sustainable development of society.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Program Outcomes (POs)
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identity, formulate complex engineering problems reaching substantiated
conclusions using principles of Computer Engineering.
3. Design/development of solutions: Design / develop solutions for complex engineering
problems and design system components or processes that meet the specified needs with
appropriate consideration for the society.
4. Conduct investigations of complex problems: Use knowledge for the design of experiments,
analysis, interpretation of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select and apply appropriate techniques and modern engineering
tools, including predictions and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply the knowledge to assess social issues and the responsibilities
relevant to engineering practices.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in social and environmental contexts, and demonstrate the knowledge for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and teamwork: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively such as being able to comprehend and write
effective reports and design documentation, make effective presentations.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management skills and apply the skills to manage projects effectively.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Academic Year 2024-2025

CLASS: TE COMPUTER SEM: VI SUBJECT: (CSL603)

Lab Outcome
1. To develop and demonstrate mobile applications using various tools
2. Students will articulate the knowledge of GSM, CDMA & Bluetooth technologies and
demonstrate it.
3. Students will able to carry out simulation of frequency reuse , hidden terminal problem
4. To develop security algorithms for mobile communication network
5. To demonstrate simulation and compare the performance of Wireless LAN

The software's like Android Studio, J2ME, NS2, NS3 and any other software which is suitable
are recommended for performing the practical.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Experiment List

S.N. Practical Title CO


1 Implementation a Bluetooth network with application as transfer of a file from one
CO2
device to another.
To implement a basic function of Code Division Multiple Access (CDMA) to
2 test the orthogonality and autocorrelation of a code to be used for CDMA CO2
operation. Write an application based on the above concept.

3 Implementation of GSM security algorithms (A3/A5/A8) CO2

4 To develop a Simple Android Application that uses Layout Managers and Event CO3
Listeners
5 Write an application that draws basic graphical primitives on the screen CO1

6 Develop an application that uses GUI components CO1

7 Implementation of income tax/loan EMI calculator and deploy the same on real CO1
devices.
8 Develop a native application that makes use of GPS location CO1

9 Develop an application that makes use of database. CO1

10 Study of security tools (like Kismet,Netstumbler) CO4

Prof. Tulsidas R. Mane Dr. Rais A. Mulla

Subject In-charge (HOD Computer Dept)

VPPCOE&VA-DM-COMP-FF-06

EXPERIMENT NO. 1

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Aim: Implementation a Bluetooth network with application as transfer of a file from one device to
another.

Theory: The Bluetooth technology aims at so-called ad-hoc piconets, which are local area networks
with a very limited coverage and without the need for an infrastructure. This is a different type of
network is needed to connect different small devices in close proximity (about 10 m) without expensive
wiring or the need for a wireless infrastructure

1. code for activity.java


package com.aqua.bluetoothfiletransfer.indragni;

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


import java.io.File;
import java.util.List;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.aqua.bluetoothfiletransfer.R;
public class MainActivity extends AppCompatActivity {
private static final int DISCOVER_DURATION = 300;

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


private static final int REQUEST_BLU = 1;
String path;
private static final String[] INITIAL_PERMS =
{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS,
Manifest.permission.CAMERA,
Manifest.permission.ACCESS_FINE_LOCATION};
private static final int INITIAL_REQUEST = 1337;
private static final int REQUEST_WRITE_STORAGE = INITIAL_REQUEST + 4;
TextView textView_FileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainn);
textView_FileName = (TextView) findViewById(R.id.textView_FileName);
if (!canAccessLocation() || !canAccessCamera() || !canAccessWriteStorage() ||
!canAccessReadStorage() || !canAccessReadContacts() || !canAccessWriteContacts()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_WRITE_STORAGE:

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


if (canAccessWriteStorage()) {
//reload my activity with permission granted or use the features what required the
permission
System.out.println("permission grantedddd");
} else {
Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot
function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
break;
}
}
public void sendViaBluetooth(View v) {
if (path == null) {
Toast.makeText(this, "Please select file first", Toast.LENGTH_SHORT).show();
return;
}
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device",
Toast.LENGTH_LONG).show();
} else {
enableBluetooth();
}
}
public void getFile(View v) {
Intent mediaIntent = new Intent(Intent.ACTION_GET_CONTENT);
mediaIntent.setType("*/*"); //set mime type as per requirement
startActivityForResult(mediaIntent, 1001);
}

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


public void enableBluetooth() {
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("*/*");
File f = new File(path);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
PackageManager pm = getPackageManager();
List<ResolveInfo> appsList = pm.queryIntentActivities(intent, 0);
if (appsList.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : appsList) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
if (!found) {

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Toast.makeText(this, "Bluetooth havn't been found",
Toast.LENGTH_LONG).show();
} else {
intent.setClassName(packageName, className);
startActivity(intent);
}
}
} else if (requestCode == 1001
&& resultCode == Activity.RESULT_OK) {
Uri uriPath = data.getData();
Log.d("", "Video URI= " + uriPath);
path = getPath(this, uriPath);// "/mnt/sdcard/FileName.mp3"
System.out.println("pathhhh " + path);
textView_FileName.setText(path);
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG)
.show();
}
}

private boolean canAccessWriteStorage() {


return (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE));
}
private boolean canAccessReadStorage() {
return (hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE));
}
private boolean canAccessReadContacts() {
return (hasPermission(Manifest.permission.READ_CONTACTS));

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


}
private boolean canAccessWriteContacts() {
return (hasPermission(Manifest.permission.WRITE_CONTACTS));
}
private boolean canAccessCamera() {
return (hasPermission(Manifest.permission.CAMERA));
}
private boolean canAccessLocation() {
return (hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
private boolean hasPermission(String perm) {
return (PackageManager.PERMISSION_GRANTED ==
ContextCompat.checkSelfPermission(this, perm));
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKatOrAbove = Build.VERSION.SDK_INT >=
Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKatOrAbove && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}

/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}

2. code for activity.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">

<TextView
android:id="@+id/textView_FileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Please select file"
android:textSize="18sp" />

<Button
android:id="@+id/button_GetFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="getFile"
android:text="Get file from device" />

<Button
android:id="@+id/button_SendFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendViaBluetooth"
android:text="Send via Bluetooth" />

</LinearLayout>

3. code for manifest

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 2

Aim: To implement a basic function of Code Division Multiple Access (CDMA) to test the
orthogonality and autocorrelation of a code to be used for CDMA operation. Write an application
based on the above concept.
Theory:
Code-division multiple access (CDMA) is a channel access method used by
various radio communication technologies. CDMA is an example of multiple access, where
several transmitters can send information simultaneously over a single communication channel.
This allows several users to share a band of frequencies (see bandwidth). To permit this without
undue interference between the users, CDMA employs spread spectrum technology and a special
coding scheme (where each transmitter is assigned a code).
CDMA is used as the access method in many mobile phone standards. IS-95, also called
"cdmaOne", and its 3G evolution CDMA2000, are often simply referred to as "CDMA",
but UMTS, the 3G standard used by GSM carriers, also uses "wideband CDMA", or W-CDMA,
as well as TD-CDMA and TD-SCDMA, as its radio technologies.
The intended 4G successor to CDMA2000 was UMB (Ultra Mobile Broadband); however, in
November 2008, Qualcomm announced it was ending development of the technology, favoring
LTE instead
CDMA Orthogonality:
Techniques generally used are direct sequence spread spectrum modulation (DS-CDMA),
frequency hopping or mixed CDMA detection (JDCDMA). Here, a signal is generated which
extends over a wide bandwidth. A code called spreading code is used to perform this action.
Using a group of codes, which are orthogonal to each other, it is possible to select a signal with a
given code in the presence of many other signals with different orthogonal codes.
CDMA Autocorrelation:
Autocorrelation of the sequence, it determines the ability to synchronize and lock the spreading
code for the received signal.

What is CDMA?

CDMA stands for Code Division Multiple Access.


It is a digital cellular standard that utilizes spread-Spectrum Technology.
It spreads the signal over a fully available spectrum or over multiple channels through division.
It is a more secure and private line.
It has good voice and data communication capabilities.
The information is sent simultaneously through several transmitters over a single communication
channel.
Procedure:

1. The station encodes its data bit as follows.


If bit = 1 then +1

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


If bit = 0 then -1
no signal(interpreted as 0) if station is idle

2. Each station is allocated a different orthogonal sequence (code) which is N bit long for N stations

3. Each station does a scalar multiplication of its encoded data bit and code sequence.

4. The resulting sequence is then stored on the channel.

5. Since the channel is common, amplitudes add up and hence resultant channel sequence is the sum of
sequences from all channels.

6. If station 1 wants to listen to station 2, it multiplies (inner product) the channel sequence with code of
station S2.

7. The inner product is then divided by N to get data bit transmitted from station 2.

mport numpy as np
c1=[1,1,1,1]
c2=[1,-1,1,-1]
c3=[1,1,-1,-1]
c4=[1,-1,-1,1]
rc=[]

print("Enter the data bits :")

d1=int(input("Enter D1 :"))
d2=int(input("Enter D2 :"))
d3=int(input("Enter D3 :"))
d4=int(input("Enter D4 :"))
r1=np.multiply(c1,d1)
r2=np.multiply(c2,d2)
r3=np.multiply(c3,d3)
r4=np.multiply(c4,d4)
resultant_channel=r1+r2+r3+r4;
print("Resultant Channel",resultant_channel)
Channel=int(input("Enter the station to listen for C1=1 ,C2=2, C3=3 C4=4 : "))

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


if Channel==1:
rc=c1
elif Channel==2:
rc=c2
elif Channel==3:
rc=c3
elif Channel==4:
rc=c4
inner_product=np.multiply(resultant_channel,rc)

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


print("Inner Product",inner_product)
res1=sum(inner_product)

data=res1/len(inner_product)
print("Data bit that was sent",data)
output

Conclusion:
Thus, we have studied the CDMA code to test autocorrelation and orthogonality of codes and
executed the same using the java code as above and got proper output for it.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 3

Aim: Implementation of GSM security algorithms (A3/A5/A8)

Theory:
GSM offers several security services using confidential information stored in the AuC and in the
individual SIM (which is plugged into an arbitrary MS). Three algorithms have been specified to
provide security services in GSM. Algorithm A3 is used for authentication, A5 for encryption, and A8
for the generation of a cipher key.
Authentication Algorithm :
1. The network sends the AUTHENTICATION REQUEST message containing the RAND.
2. The phone receives the RAND, and passes it to the SIM, in the RUN GSM ALGORITHM
command.
3. The SIM runs the A3 algorithm, and returns the SRES to the phone.
4. The phone transmits the SRES to the network in the AUTHENTICATION RESPONSE
message.
5. The network compares the SRES with its own SRES. If they match, the transaction may
proceed. Otherwise, the network either decides to repeat the authentication procedure with IMSI
if the TMSI was used, or returns an AUTHENTICATION REJECT message.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Encryption Algorithm :
1. After authentication, MS and BSS can start using encryption by applying the cipher key Kc
2. Kc is generated using the individual key Ki and a random value by applying the algorithm A8.
3. The SIM in the MS and the network both calculate the same Kc based on the random value
RAND.
4. The key Kc itself is not transmitted over the air interface.
5. MS and BTS can now encrypt and decrypt data using the algorithm A5 and the cipher key Kc.
6. Kc should be a 64 bit key which is not very strong, but is at least a good protection against
simple eavesdropping.

{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


"name": "GSMA3.ipynb",
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "YayZF380O-Ic",
"outputId": "051a7b18-5f6e-4616-80c2-9dd7ce253ab4"
},
"source": [
"import random\n",
"\n",
"k=random.getrandbits(128)\n",
"m=random.getrandbits(128)\n",
"kb=bin(k)[2:]\n",
"mb=bin(m)[2:]\n",
"kbl=kb[0:64]\n",
"kbr=kb[64:]\n",
"mbl=mb[0:64]\n",
"mbr=mb[64:]\n",
"a1=int(kbl,2)^int(mbr,2)\n",
"a2=int(kbr,2)^int(mbl,2)\n",
"a3=a1^a2\n",
"a4=bin(a3)[2:].zfill(64)\n",
"a5=a4[0:32]\n",
"a6=a4[32:]\n",
"a7=int(a5,2)^int(a6,2)\n",
"print(\"128 Bit Key = \",kb)\n",

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


"print(\"128 Random Bits Generated = \",mb)\n",
"print(\"RES/SRES = \",bin(a7)[2:].zfill(len(a5)))"
],
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"128 Bit Key =
11111011101001100100000100100110001001110011110100111010110100011110001110000011
"128 Random Bits Generated =
11000001000100010110001011100100110110101100110010001101011100010010000101001010
"RES/SRES = 11110110110100000010111110001101\n"
]
}
]
}
]
}

import random

k=random.getrandbits(128)
m=random.getrandbits(128)
kb=bin(k)[2:]
mb=bin(m)[2:]
kbl=kb[0:64]
kbr=kb[64:]
mbl=mb[0:64]
mbr=mb[64:]
a1=int(kbl,2)^int(mbr,2)
a2=int(kbr,2)^int(mbl,2)
a3=a1^a2
a4=bin(a3)[2:].zfill(64)
a5=a4[0:32]
a6=a4[32:]
a7=int(a5,2)^int(a6,2)
print("128 Bit Key = ",kb)
print("128 Random Bits Generated = ",mb)
print("RES/SRES = ",bin(a7)[2:].zfill(len(a5)))

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


128 Bit Key =
11111011101001100100000100100110001001110011110100111010110100011110001110000011110
11101110110111010100010110101000111010001
128 Random Bits Generated =
11000001000100010110001011100100110110101100110010001101011100010010000101001010010
000010011110000001000011001001111111000100
RES/SRES = 11110110110100000010111110001101

Conclusion: Thus the program for GSM security is implemented and verified.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 4

Aim: To develop a Simple Android Application that uses Layout Managers and Event Listeners.
Procedure:Creating a New project:
 Open Android Stdio and then click on File -> New -> New project.

 Then type the Application name as “ex.no.2″ and click Next.

 Then select the Minimum SDK as shown below and click Next.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 Then select the Empty Activity and click Next.

 Finally click Finish.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 It will take some time to build and load the project.
 After completion it will look as given below.

Creating Second Activity for the Android Application:


 Click on File -> New -> Activity -> Empty Activity.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 Type the Activity Name as SecondActivity and click Finish button.

 Thus Second Activity For the application is created.


Designing layout for the Android Application:
Designing Layout for Main Activity:
 Click on app -> res -> layout -> activity_main.xml.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 Now click on Text as shown below.

 Then delete the code which is there and type the code as given below.
Code for Activity_main.xml:?
<?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=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:text="Details Form"

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


android:textSize="25sp"
android:gravity="center"/>
</LinearLayout>

<GridLayout
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:layout_marginBottom="200dp"
android:columnCount="2"
android:rowCount="3">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="0"
android:text="Name"
android:textSize="20sp"
android:gravity="center"/>

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="1"
android:ems="10"/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="0"
android:text="Reg.No"
android:textSize="20sp"
android:gravity="center"/>

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


android:layout_row="1"
android:layout_column="1"
android:inputType="number"
android:ems="10"/>

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="0"
android:text="Dept"
android:textSize="20sp"
android:gravity="center"/>

<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="1"
android:spinnerMode="dropdown"/>

</GridLayout>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginBottom="150dp"
android:text="Submit"/>

</RelativeLayout>
 Now click on Design and your activity will look as given below.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 So now the designing part of Main Activity is completed.
Designing Layout for Second Activity:
 Click on app -> res -> layout -> activity_second.xml.

 Now click on Text as shown below.

 Then delete the code which is there and type the code as given below.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Code for Activity_second.xml:
?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.devang.exno2.SecondActivity"
android:orientation="vertical"
android:gravity="center">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>

</LinearLayout>
 Now click on Design and your activity will look as given below.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 So now the designing part of Second Activity is also completed.
Java Coding for the Android Application:
Java Coidng for Main Activity:
 Click on app -> java -> com.example.exno2 -> MainActivity.

Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
?
package com.example.exno2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class MainActivity extends AppCompatActivity {

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


//Defining the Views
EditText e1,e2;
Button bt;
Spinner s;

//Data for populating in Spinner


String [] dept_array={"CSE","ECE","IT","Mech","Civil"};

String name,reg,dept;

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

//Referring the Views


e1= (EditText) findViewById(R.id.editText);
e2= (EditText) findViewById(R.id.editText2);

bt= (Button) findViewById(R.id.button);

s= (Spinner) findViewById(R.id.spinner);

//Creating Adapter for Spinner for adapting the data from array to Spinner
ArrayAdapter adapter= new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item,dept_arra
s.setAdapter(adapter);

//Creating Listener for Button


bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

//Getting the Values from Views(Edittext & Spinner)


name=e1.getText().toString();
reg=e2.getText().toString();
dept=s.getSelectedItem().toString();

//Intent For Navigating to Second Activity


Intent i = new Intent(MainActivity.this,SecondActivity.class);

//For Passing the Values to Second Activity


i.putExtra("name_key", name);
i.putExtra("reg_key",reg);
i.putExtra("dept_key", dept);

startActivity(i);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


}
});
}
}
 So now the Coding part of Main Activity is completed.
Java Coding for Second Activity:
 Click on app -> java -> com.example.exno2 -> SecondActivity.

 Then delete the code which is there and type the code as given below.
Code for SecondActivity.java:
?
package com.example.exno2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

TextView t1,t2,t3;

String name,reg,dept;

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

t1= (TextView) findViewById(R.id.textView1);


t2= (TextView) findViewById(R.id.textView2);
t3= (TextView) findViewById(R.id.textView3);

//Getting the Intent


Intent i = getIntent();

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


//Getting the Values from First Activity using the Intent received
name=i.getStringExtra("name_key");
reg=i.getStringExtra("reg_key");
dept=i.getStringExtra("dept_key");

//Setting the Values to Intent


t1.setText(name);
t2.setText(reg);
t3.setText(dept);

}
}
 So now the Coding part of Second Activity is also completed.
 Now run the application to see the output.
Output:

Result:Thus a Simple Android Application that uses Layout Managers and Event Listeners is
developed and executed successfully.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 5

Aim: Write an application that draws basic graphical primitives on the screen.

1. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent">

<ImageView

android:layout_width="match_parent"

android:layout_height="match_parent"

android:id="@+id/imageView" />

</RelativeLayout>

2. MainActivity.java:

package com.example.exp11;

import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.drawable.BitmapDrawable;

import android.os.Bundle;

import android.widget.ImageView;

public class MainActivity extends Activity

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


@Override

public void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//Creating a Bitmap

Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

//Setting the Bitmap as background for the ImageView

ImageView i = (ImageView) findViewById(R.id.imageView);

i.setBackgroundDrawable(new BitmapDrawable(bg));

//Creating the Canvas Object

Canvas canvas = new Canvas(bg);

//Creating the Paint Object and set its color & TextSize

Paint paint = new Paint();

paint.setColor(Color.BLUE);

paint.setTextSize(50);

//To draw a Rectangle

canvas.drawText("Rectangle", 420, 150, paint);

canvas.drawRect(400, 200, 650, 700, paint);

//To draw a Circle

canvas.drawText("Circle", 120, 150, paint);

canvas.drawCircle(200, 350, 150, paint);

//To draw a Square

canvas.drawText("Square", 120, 800, paint);

canvas.drawRect(50, 850, 350, 1150, paint);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


//To draw a Line

canvas.drawText("Line", 480, 800, paint);

canvas.drawLine(520, 850, 520, 1150, paint);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 6

Aim: Develop an application that uses GUI components.

1. Code for Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:gravity="center"
android:text="Hello World!"
android:textSize="25sp"
android:textStyle="bold" />

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:gravity="center"
android:text="Change font size"
android:textSize="25sp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:gravity="center"
android:text="Change color"
android:textSize="25sp" />
</LinearLayout>

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


2. Code for MainActivity.java:

package com.example.exno1;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity


{
int ch=1;
float font=30;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView t= (TextView) findViewById(R.id.textView);
Button b1= (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
t.setTextSize(font);
font = font + 5;
if (font == 50)
font = 30;
}
});

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Button b2= (Button) findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (ch) {
case 1:
t.setTextColor(Color.RED);
break;
case 2:
t.setTextColor(Color.GREEN);
break;
case 3:
t.setTextColor(Color.BLUE);
break;
case 4:
t.setTextColor(Color.CYAN);
break;
case 5:
t.setTextColor(Color.YELLOW);
break;
case 6:
t.setTextColor(Color.MAGENTA);
break;
}
ch++;
if (ch == 7)
ch = 1;
}
});
}
}

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


TE COMP Subject: Mobile Computing Lab Subject Code: CSL603
EXPERIMENT NO. 7

Aim: Implementation of income tax/loan EMI calculator and deploy the same on real devices.

Here’s the formula to calculate EMI

where,
E is EMI
P is Principal Loan Amount
r is the rate of interest calculated on monthly basis.
n is loan term/tenure / duration in number of months

1. Code for activity_main.xml.

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="abu.emicalculator.MainActivity"
android:layout_height="match_parent">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp">

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout_principal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
android:id="@+id/principal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="number"
android:digits="0123456789."
android:hint="@string/hint_principal" />

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout_interest"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
android:id="@+id/interest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="number"
android:digits="0123456789."
android:hint="@string/hint_interest" />

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout_tenure"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
android:id="@+id/years"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:digits="0123456789."
android:hint="@string/hint_years" />
</android.support.design.widget.TextInputLayout>

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


<Button android:id="@+id/btn_calculate2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Calculate"
android:background="@color/colorPrimary"
android:layout_marginTop="40dp"
android:textColor="@android:color/white"/>

<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout_emi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp">

<EditText
android:id="@+id/emi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxEms="0"
android:inputType="number"
android:hint="@string/hint_emi" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout_total_Interest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">

<EditText
android:id="@+id/interest_total"
android:layout_width="match_parent"
android:layout_height="wrap_content"

android:inputType="number"
android:hint="@string/hint_interest_total" />
</android.support.design.widget.TextInputLayout>

</LinearLayout>
</android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

2. Go to (gradle scripts ⇒ build.gradle(moduleapp). And, add the below code.


compile 'com.android.support:appcompat-v7:23.4.0'

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


compile 'com.android.support:design:23.1.0'

3. Go to (App ⇒ Res ⇒values⇒String.xml).


<resources>
<string name="app_name">EMI Calculator</string>
<string name="hint_principal">Principal Amount ₹</string>
<string name="hint_interest">Interest rate per Year %</string>
<string name="hint_years">How Many Years</string>
<string name="hint_emi">EMI ₹</string>
<string name="hint_interest_total">Total Interest for Loan ₹</string>
</resources>

4. code for Main Activity.java.

package abu.emicalculator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

Button emiCalcBtn;

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


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

final EditText P = (EditText)findViewById(R.id.principal);


final EditText I = (EditText)findViewById(R.id.interest);
final EditText Y = (EditText)findViewById(R.id.years);
final EditText TI = (EditText)findViewById(R.id.interest_total);

final EditText result = (EditText)findViewById(R.id.emi) ;


emiCalcBtn = (Button) findViewById(R.id.btn_calculate2);
emiCalcBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void on Click(View v) {

String st1 = P.getText().toString();


String st2 = I.getText().toString();
String st3 = Y.getText().toString();

if (TextUtils.isEmpty(st1)) {
P.setError("Enter Prncipal Amount");
P.requestFocus();
return;
}

if (TextUtils.isEmpty(st2)) {
I.setError("Enter Interest Rate");
I.requestFocus();
return;
}

if (TextUtils.isEmpty(st3)) {
Y.setError("Enter Years");
Y.requestFocus();
return;
}
float p = Float.parseFloat(st1);
float i = Float.parseFloat(st2);
float y = Float.parseFloat(st3);

float Principal = calPric(p);

float Rate = calInt(i);

float Months = calMonth(y);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


float Dvdnt = calDvdnt( Rate, Months);

float FD = calFinalDvdnt (Principal, Rate, Dvdnt);

float D = calDivider(Dvdnt);

float emi = calEmi(FD, D);

float TA = calTa (emi, Months);

float ti = calTotalInt(TA, Principal);

result.setText(String.valueOf(emi));

TI.setText(String.valueOf(ti));

}
});
}

public float calPric(float p) {

return (float) (p);

public float calInt(float i) {

return (float) (i/12/100);

public float calMonth(float y) {

return (float) (y * 12);

public float calDvdnt(float Rate, float Months) {

return (float) (Math.pow(1+Rate, Months));

public float calFinalDvdnt(float Principal, float Rate, float Dvdnt) {

return (float) (Principal * Rate * Dvdnt);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


}

public float calDivider(float Dvdnt) {

return (float) (Dvdnt-1);

}
public float calEmi(float FD, Float D) {

return (float) (FD/D);


}

public float calTa(float emi, Float Months) {

return (float) (emi*Months);

public float calTotalInt(float TA, float Principal) {

return (float) (TA - Principal);

}
}

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 8

Aim: Develop a native application that makes use of GPS location.


Theory : Sometime we need to get GPS coordinates in android. Through coordinate we can calculate
current location more details like City Name.
What this app does?
Check gps is enable or disable.
Get gps coordinates.
Get the current city name.

1. code for GetCurrentLocation.java

package com.rdc;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class GetCurrentLocation extends Activity


implements OnClickListener {

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


private LocationManager locationMangaer=null;
private LocationListener locationListener=null;

private Button btnGetLocation = null;


private EditText editLocation = null;
private ProgressBar pb =null;

private static final String TAG = "Debug";


private Boolean flag = false;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//if you want to lock screen for always Portrait mode


setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);

pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);

editLocation = (EditText) findViewById(R.id.editTextLocation);

btnGetLocation = (Button) findViewById(R.id.btnLocation);


btnGetLocation.setOnClickListener(this);

locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {

Log.v(TAG, "onClick");

editLocation.setText("Please!! move your device to"+


" see the changes in coordinates."+"\nWait..");

pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();

locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}

/*----Method to Check GPS is enable or disable ----- */


private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;

} else {
return false;
}
}

/*----------Method to create an AlertBox ------------- */


protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


}

/*----------Listener class to get coordinates ------------- */


private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {

editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);

/*----------to get City-Name from coordinates ------------- */


String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


}
}
2. cod for main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Current Location and City Name"
android:layout_weight="0.20"
android:gravity="center"
android:textSize="20sp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:id="@+id/editTextLocation"
android:editable="false">
<requestFocus></requestFocus>
</EditText>
<LinearLayout
android:id="@+id/layButtonH"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_weight="0.15">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"
android:id="@+id/btnLocation"></Button>
</LinearLayout>
<LinearLayout
android:id="@+id/layloadingH"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:layout_width="fill_parent"
android:gravity="center">
<ProgressBar
android:layout_width="wrap_content"
android:id="@+id/progressBar1"
android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


</LinearLayout>
3. code for AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rdc"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
</uses-permission>
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".GetCurrentLocation"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

</intent-filter> </activity>
</application>
</manifest>

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 09

Aim: Develop an application that makes use of database.


1. code for activity.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="20dp"
android:text="Student Details"
android:textSize="30sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"
android:text="Enter Rollno:"
android:textSize="20sp" />

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


<EditText
android:id="@+id/Rollno"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textSize="20sp" />
<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


android:text="Enter Marks:"
android:textSize="20sp" />
<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />
<Button
android:id="@+id/Delete"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="300dp"
android:text="Delete"
android:textSize="30dp" />
<Button
android:id="@+id/Update"

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />
<Button
android:id="@+id/View"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="400dp"
android:text="View"
android:textSize="30dp" />
<Button
android:id="@+id/ViewAll"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_x="100dp"
android:layout_y="500dp"
android:text="View All"
android:textSize="30dp" />
</AbsoluteLayout>
2. code for activity.java
package com.example.database;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements OnClickListener {
EditText Rollno,Name,Marks;
Button Insert,Delete,Update,View,ViewAll;
SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);
ViewAll=(Button)findViewById(R.id.ViewAll);
Insert.setOnClickListener(this);
Delete.setOnClickListener(this);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);
// Creating database and table
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name
VARCHAR,marks VARCHAR);");
}
public void onClick(View view)
{
// Inserting a record to the Student table
if(view==Insert)
{
// Checking for empty fields
if(Rollno.getText().toString().trim().length()==0||
Name.getText().toString().trim().length()==0||
Marks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student VALUES('"+Rollno.getText()+"','"+Name.getText()+
"','"+Marks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
// Deleting a record from the Student table
if(view==Delete)
{

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",
null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
// Updating a record in the Student table
if(view==Update)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


null);
if(c.moveToFirst()) {
db.execSQL("UPDATE student SET name='" + Name.getText() + "',marks='" +
Marks.getText() +
"' WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Modified");
}
else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}
// Display a record from the Student table
if(view==View)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",
null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
// Displaying all the records
if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{ Rollno.setText("");
Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}
}

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Conclusion : Hence we studied the Develop an application that makes use of database.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 10

Aim :- Study of security tools (like Kismet,Netstumbler)


Abstract—Wireless networks have been very popular in recent times and especially in the last two
decades. This popularity is due to a world-wide adoption of various wireless standards and a rapid
development of wireless hardware to support higher throughputs and lower latency requirements. As
more and more data gets transmitted over wireless networks, ensuring a secure communication is
essential. Consequently, understanding security tools becomes essential. This paper studies two popular
security tools: Kismet and NetStumbler. We provide a thorough understanding of these tools and their
functioning. I.
INTRODUCTION : Wireless networks are more convenient than wired networks and allow you to
move from room to room in your home [1]–[8]. Further, with a advancement in wireless hardware,
higher throughput and lower latency support has become possible [9]–[16]. But they can also be more
vulnerable if not properly secured. If our wireless network is ’unsecured’ or ‘open’ then an intruder can
easily gain access to our internal network resources as well as to the Internet, all without our consent.
Once the intruder has access to our network, he/she can use it for a variety of operations, such as: • To
steal your Internet bandwidth. • To perform disruptive or illegal acts. • To steal your sensitive
information. • To perform Denial-of-Service (DoS) attacks to make the network unusable by sending
out false requests. • To infect the network with malicious threats Thus, wireless networking is
inherently risky because we are transmitting information via radio waves. Data from your wireless
network can be intercepted just like signals from our cellular or cordless phones. Whenever we use a
wireless connection, we might want to ensure that our communications and files are private and
protected. If our transmissions are not secure, it may be possible for others to intercept our e-mails,
examine our files and records, and use our network and Internet connection to distribute their own
messages and communications. Hence we need security in wireless network. II. KISMET Kismet is a
network detector, packet sniffer, and intrusion detection system for 802.11 wireless LANs. Kismet will
work with any wireless card which supports raw monitoring mode, and can sniff 802.11a, 802.11b,
802.11g, and 802.11n traffic. The program runs under Linux, FreeBSD, NetBSD, OpenBSD, and Mac
OS X. The client can also run on Microsoft Windows, although, aside from external drones , there’s
only one supported wireless hardware available as packet source. Distributed under the GNU General
Public License, Kismet is free software. A. Working of kismet Kismet differs from other wireless
network detectors in working passively. Namely, without sending any loggable packets, it is able to
detect the presence of both wireless access points and wireless clients, and to associate them with each
other. It is also the most widely used and up to date open source wireless monitoring tool.Refer fig. 1 to
view at explanation of the headings displayed in Kismet. 1. Kismet also includes basic wireless IDS
features such as detecting active wireless sniffing programs including NetStumbler, as well as a
number of wireless network attacks. 2. Kismet also features the ability to detect default or ”not
configured” networks, probe requests, and determine what level of wireless encryption is used on a
given access point. 3. Kismet also supports logging of the geographical our transmissions are not
secure, it may be possible for others to intercept our e-mails, examine our files and records, and use our
network and Internet connection to distribute their own messages and communications. Hence we need
security in wireless network. II. KISMET Kismet is a network detector, packet sniffer, and intrusion
detection system for 802.11 wireless LANs. Kismet will work with any wireless card which supports
raw monitoring mode, and can sniff 802.11a, 802.11b, 802.11g, and 802.11n traffic. The program runs

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


under Linux, FreeBSD, NetBSD, OpenBSD, and Mac OS X. The client can also run on Microsoft
Windows, although, aside from external drones , there’s only one supported wireless hardware
available as packet source. Distributed under the GNU General Public License, Kismet is free software.
A. Working of kismet Kismet differs from other wireless network detectors in working passively.
Namely, without sending any loggable packets, it is able to detect the presence of both wireless access
points and wireless clients, and to associate them with each other. It is also the most widely used and
up to date open source wireless monitoring tool.Refer fig. 1 to view at explanation of the headings
displayed in Kismet.
1. Kismet also includes basic wireless IDS features such as detecting active wireless sniffing programs
including NetStumbler, as well as a number of wireless network attacks.
2. Kismet also features the ability to detect default or ”not configured” networks, probe requests, and
determine what level of wireless encryption is used on a given access point. 3. Kismet also supports
logging of the geographical

coordinates of the network if the input from a GPS receiver is additionally available. 4. Kismet works
with a lot of wireless cards supporting ”monitor” mode. This mode captures packets without being able
to associate in the same time with an access point and require privileges rights. 5. Kismet detects
networks by passively sniffing providing it the advantages to discover the ”hidden” wireless networks
and being itself undetectable. B.
Advantage of kismet
• It results is very good for small area.
• It has a Server – Client architecture
• Drones: distributed kismet servers running on remote devices, reporting back to central server, allow
for the building of distributed reporting and intrusion detection systems.
• Kismet is powerful - especially when combined with other tools like wireshark, nmap. C.
Disadvantage of kismet
• It takes long time to search networks.
• It can only identify the wireless network (WiFi) in a small area, if the range is more it cannot work
properly. D. System requirements (a) Kismet – packet sniffer (b) Spectrum analyzers: airview, wispy
(c) General networking tools : wireshark, ntop, mrtg, rrdtool, nmap etc. (d) WEP/WPA/WPA2
cracking: aircrack etc (e) It will work (at some level) on any operating system which has POSIX

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


compatibility, however for it to do native packet capturing it needs drivers which are capable of
reporting packets in rfmon. Remote sources such WSP100 or Drones can be used on any platform we
can get kismet to compile.
(f) Kismet will work with any distribution of Linux. Currently, Linux is the recommended platform for
running Kismet because it has largest selection of rfmon capable drivers.
NETSTUMBLER
NetStumbler (also known as Network Stumbler) is a tool for Windows that facilitates detection of
Wireless LANs using the 802.11b, 802.11a and 802.11g WLAN standards. It runs on Microsoft
Windows operating systems from Windows 2000 to Windows XP. The program is commonly used for:
• Wardriving • Verifying network configurations • Finding locations with poor coverage in a WLAN •
Detecting causes of wireless interference • Detecting unauthorized (”rogue”) access points • Aiming
directional antennas for long-haul WLAN links The NetStumbler application is a Windows-based tool
generally used to discover WLAN networks running on 802.11 a/b/g standards. It helps detect other
networks that may cause interference to your network, and is generally used for war driving purposes
by attackers. It can also find out poor coverage areas in the WLAN network, and helps the
administrator set up the network the way it is intended to be. A. Working of NetStumbler 1. By default,
NetStumbler immediately starts scanning for beacons when you launch it. When NetStumbler starts, it
creates a new file with the year, month, day, and 24-hour time listed serially without delimiters. For
instance, if it’s April 21, 2002 at 3:15 P.M., it will create a file called 200204211515. You can use this
filename convention to help find data files created over the course of days or years. 2. Refer to fig. 2
that shows the NetStumbler screen immediately after startup. As you can see at the bottom of the
screen, this example workstation doesn’t have an installed wireless card. I’ve intentionally not inserted
the LAN card so you can see an empty list. NetStumbler starts up ready to scan.

Advantage of NetStumbler
• NetStumbler is a very useful tool that any wireless network administrator should be using periodically

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


to determine not only the range of their wireless network, but also what wireless networks are available
within their vicinity. • First, determining the range of your wireless network will help you be able to
provide better service. Armed with this information you can adjust antenna directions or AP placement
to provide maximum coverage within your environment, and as little coverage as possible outside of
the building/campus. • Secondly, NetStumbler is a great tool for determining whether there are any
additional wireless networks nearby. These networks could potentially be rogue APs that have been
placed behind your firewall by uninformed users, not secured according to corporate standards, and
thus a major security risk.
Disadvantage of NetStumbler
• NetStumbler has a tendency to be a virtual fire hose of information, overloading the casual user. If
you know what you are looking for, and are familiar with NetStumbler then there is a great deal of
information available to you in its screens, but this can be intimidating. • Another thing that was true
for some of the earlier versions of NetStumbler is that it depended upon the type of wireless card you
have, specifically, the manufacturer of the chipset used for 802.11 modulation. As time has passed
more and more cards and chipsets have been made compatible with NetStumbler. • Also, NetStumbler
on its own does nothing to tell a user whether the network is secure or not, it simply provides all of the
relevant details with regard to the wireless network. Used in conjunction with other tools (WEPCrack,
AirSnort, etc) NetStumbler is a useful tool for an end to end evaluation of wireless security, however
many of the competitors to NetStumbler easily bundle these additional tools. This bundling makes the
additional tools easier to use, at the sacrifice of flexibility within the tool. Some would consider this is a
pro for NetStumbler, but generally it is regarded as a mixed bag. • The software doesn’t officially work
on Windows Vista (or Mac). • NetStumbler isn’t 100% passive. It uses Active Scanning and sends out
a probe request about once a second, and reports the responses. Normally, this isn’t a big deal but this
means in a 100% no wireless zone NetStumbler can be detected. • NetStumbler does not detect wireless
stations. Access points are detected by recording which ones respond to probe requests, which also
means it can not detect wireless stations since they don’t respond to probe requests (b) General
networking tools: wireshark, ntop, mrtg,rrdtool, nmap etc. (c) WEP/WPA/WPA2 cracking: aircrack etc
The requirements for NetStumbler are somewhat complex and depend on hardware, firmware versions,
driver versions and operating system. The best way to see if it works on your system is to try it. The
following are rules of thumb that you can follow in case you cannot reach the web site for some reason.
1) This version of NetStumbler requires Windows 2000, Windows XP, or better. 2) The Proxim models
8410-WD and 8420-WD are known to work. The 8410-WD has also been sold as the Dell TrueMobile
1150, Compaq WL110, Avaya Wireless 802.11b PC Card, and others. 3) Most cards based on the
Intersil Prism/Prism2 chip set also work. 4) Most 802.11b, 802.11a and 802.11g wireless LAN adapters
should work on Windows XP. Some may work on Windows 2000 too. Many of them report inaccurate
Signal strength, and if using the “NDIS 5.1” card access method then Noise level will not be reported.
This includes cards based on Atheros, Atmel, Broadcom, Cisco and Centrino chip sets. 5) Firmware
Requirements are: If you have an old WaveLAN/IEEE card then please note that the WaveLAN
firmware (version 4.X and below) does not work with NetStumbler. If your card has this version, you
are advised to upgrade to the latest version available from Proxim’s web site. This will also ensure
compatibility with the 802.11b standard. IV.

CONCLUSION : We studied the necessity of security tools for wireless networks and also gathered
information about two popular security tools : Kismet and NetStumbler.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


VPPCOE&VA-DM-COMP-FF-06

EXPERIMENT NO. 11

Aim :- Implement an application that creates an alert upon receiving a message.

Procedure:

Creating a New project:

 Open Android Studio and then click on File -> New -> New project.

 Then type the Application name as “ex.no.10″ and












TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 click Next.
 Then select the Minimum SDK as shown below and click Next.

 Then select the Empty Activity and click Next.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 Finally click Finish.

 It will take some time to build and load the project.


 After completion it will look as given below.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Creating Second Activity for the Android Application:

 Click on File -> New -> Activity -> Empty Activity.

 Type the Activity Name as SecondActivity and click Finish button.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 Thus Second Activity For the application is created.
Designing layout for the Android Application:

 Click on app -> res -> layout -> activity_main.xml.

 Now click on Text as shown below.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 Then delete the code which is there and type the code as given below.
Code for Activity_main.xml:
?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message"
android:textSize="30sp" />

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="30sp" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:layout_gravity="center"
android:text="Notify"
android:textSize="30sp"/>

</LinearLayout>
 Now click on Design and your application will look as given below.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


 So now the designing part is completed.
Java Coding for the Android Application:

 Click on app -> java -> com.example.exno10 -> MainActivity.

 Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
?
package com.example.exno10;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


public class MainActivity extends AppCompatActivity
{
Button notify;
EditText e;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

notify= (Button) findViewById(R.id.button);


e= (EditText) findViewById(R.id.editText);

notify.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pending = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
Notification noti = new Notification.Builder(MainActivity.this).setContentTitle("New
Message").setContentText(e.getText().toString()).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pen
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERV
noti.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(0, noti);
}
});
}
}
 So now the Coding part is also completed.
 Now run the application to see the output.
Output:

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


Conclusion

Thus Android Application that creates an alert upon receiving a message is developed and
executed successfully.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


EXPERIMENT NO. 12

Aim :-
To understand the cellular frequency reuse concept to find the co-channel cells for a
particular cell. Design a game based application on the above concept.

THEORY:
Each cellular base station is allocated a group of radio channels to be used within a small
geographic area called a cell. Base stations in adjacent cells are assigned channel groups which
contain completely different channels than neighboring cells. Base station antennas are designed to
achieve the desired coverage within a particular cell. By limiting the coverage area within the
boundaries of a cell, the same group of channels may be used to cover different cells that are
separated from one another by geographic distances large enough to keep interference levels within
tolerable limits. The design process of selecting and allocating channel groups for all cellular base
stations within a system is called frequency reuse or frequency planning.

ALGORITHM:

1. start
2. Accept value of number of cells per cluster i.e. N from the user.

3. Create a function that draws a hexagon.

4. Draw a clusters with N hexagons in each cluster.

5. Write appropriate frequencies in each cluster.

6. stop.

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


ALGORITHM:
from math import *
from tkinter import *

# Base class for Hexagon shape


class Hexagon(object):
def __init__(self, parent, x, y, length, color, tags):
self.parent = parent
self.x = x
self.y = y
self.length = length
self.color = color
self.size = None
self.tags = tags
self.draw_hex()

# draw one hexagon


def draw_hex(self):
start_x = self.x
start_y = self.y
angle = 60
coords = []
for i in range(6):
end_x = start_x + self.length * cos(radians(angle * i))
end_y = start_y + self.length * sin(radians(angle * i))
coords.append([start_x, start_y])
start_x = end_x
start_y = end_y
self.parent.create_polygon(coords[0][0],
coords[0][1],
coords[1][0],
coords[1][1],
coords[2][0],
coords[2][1],
coords[3][0],
coords[3][1],
coords[4][0],
coords[4][1],
coords[5][0],
coords[5][1],
fill=self.color,
outline="black",
tags=self.tags)

# class holds frequency reuse logic and related methods


class FrequencyReuse(Tk):
CANVAS_WIDTH = 800

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


CANVAS_HEIGHT = 650
TOP_LEFT = (20, 20)
BOTTOM_LEFT = (790, 560)
TOP_RIGHT = (780, 20)
BOTTOM_RIGHT = (780, 560)

def __init__(self, cluster_size, columns=16, rows=10, edge_len=30): Tk.__init__(self)


self.textbox = None
self.curr_angle = 330
self.first_click = True
self.reset = False
self.edge_len = edge_len

self.cluster_size = cluster_size
self.reuse_list = []
self.all_selected = False
self.curr_count = 0
self.hexagons = []
self.co_cell_endp = []
self.reuse_xy = []
self.canvas = Canvas(self,
width=self.CANVAS_WIDTH,
height=self.CANVAS_HEIGHT,
bg="#4dd0e1")
self.canvas.bind("<Button-1>", self.call_back)
self.canvas.focus_set()
self.canvas.bind('<Shift-R>', self.resets)
self.canvas.pack()
self.title("Frequency reuse and co-channel selection")
self.create_grid(16, 10)
self.create_textbox()
self.cluster_reuse_calc()

# show lines joining all co-channel cells


def show_lines(self):
# center(x,y) of first hexagon
approx_center = self.co_cell_endp[0]
self.line_ids = []
for k in range(1, len(self.co_cell_endp)):

end_xx = (self.co_cell_endp[k])[0]
end_yy = (self.co_cell_endp[k])[1]

# move i^th steps


l_id = self.canvas.create_line(approx_center[0],
approx_center[1],
end_xx, end_yy)
if j == 0:

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


self.line_ids.append(l_id)
dist = 0
elif i >= j and j != 0:
self.line_ids.append(l_id)
dist = j
# rotate counter-clockwise and move j^th step
l_id = self.canvas.create_line(
end_xx, end_yy, end_xx + self.center_dist *
dist *
cos(radians(self.curr_angle - 60)),
end_yy + self.center_dist * dist *
sin(radians(self.curr_angle - 60)))
self.line_ids.append(l_id)
self.curr_angle -= 60

def create_textbox(self):
txt = Text(self.canvas,
width=80,
height=1,
font=("Helvatica", 12),
padx=10,
pady=10)
txt.tag_configure("center", justify="center")
txt.insert("1.0", "Select a Hexagon")
txt.tag_add("center", "1.0", "end")
self.canvas.create_window((0, 600), anchor='w', window=txt)

txt.config(state=DISABLED)
self.textbox = txt

def resets(self, event):


if event.char == 'R':
self.reset_grid()

# clear hexagonal grid for new i/p


def reset_grid(self, button_reset=False):
self.first_click = True
self.curr_angle = 330
self.curr_count = 0
self.co_cell_endp = []
self.reuse_list = []
for i in self.hexagons:
self.canvas.itemconfigure(i.tags, fill=i.color)

try:
self.line_ids
except AttributeError:
pass

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


else:
for i in self.line_ids:
self.canvas.after(0, self.canvas.delete, i)
self.line_ids = []

if button_reset:
self.write_text("Select a Hexagon")

# create a grid of Hexagons


def create_grid(self, cols, rows):
size = self.edge_len
for c in range(cols):
if c % 2 == 0:
offset = 0
else:
offset = size * sqrt(3) / 2
for r in range(rows):
x = c * (self.edge_len * 1.5) + 50
y = (r * (self.edge_len * sqrt(3))) + offset + 15
hx = Hexagon(self.canvas, x, y, self.edge_len,
"#fafafa",
"{},{}".format(r, c))
self.hexagons.append(hx)

# calculate reuse distance, center distance and radius of the hexagon


def cluster_reuse_calc(self):
self.hex_radius = sqrt(3) / 2 * self.edge_len
self.center_dist = sqrt(3) * self.hex_radius
self.reuse_dist = self.hex_radius * sqrt(3 * self.cluster_size)

def write_text(self, text):


self.textbox.config(state=NORMAL)
self.textbox.delete('1.0', END)
self.textbox.insert('1.0', text, "center")
self.textbox.config(state=DISABLED)

#check if the co-channels are within visible canvas


def is_within_bound(self, coords):
if self.TOP_LEFT[0] < coords[0] < self.BOTTOM_RIGHT[0] \
and self.TOP_RIGHT[1] < coords[1] < self.BOTTOM_RIGHT[1]:

return True
return False

#gets called when user selects a hexagon


#This function applies frequency reuse logic in order to
#figure out the positions of the co-channels

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


def call_back(self, evt):

selected_hex_id = self.canvas.find_closest(evt.x, evt.y)[0]


hexagon = self.hexagons[int(selected_hex_id - 1)]
s_x, s_y = hexagon.x, hexagon.y
approx_center = (s_x + 15, s_y + 25)

if self.first_click:
self.first_click = False
self.write_text(
"""Now, select another hexagon such
that it should be a co-cell of
the original hexagon."""
)
self.co_cell_endp.append(approx_center)
self.canvas.itemconfigure(hexagon.tags, fill="green")

for _ in range(6):

end_xx = approx_center[0] + self.center_dist * i *


cos(
radians(self.curr_angle))
end_yy = approx_center[1] + self.center_dist * i *
sin(
radians(self.curr_angle))

reuse_x = end_xx + (self.center_dist * j) * cos(


radians(self.curr_angle - 60))
reuse_y = end_yy + (self.center_dist * j) * sin(
radians(self.curr_angle - 60))

if not self.is_within_bound((reuse_x, reuse_y)):


self.write_text(
"""co-cells are exceeding canvas
boundary.
Select cell in the center"""
)
self.reset_grid()
break

if j == 0:
self.reuse_list.append(
self.canvas.find_closest(end_xx,
end_yy)[0])
elif i >= j and j != 0:
self.reuse_list.append(
self.canvas.find_closest(reuse_x,
reuse_y)[0])

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


self.co_cell_endp.append((end_xx, end_yy))
self.curr_angle -= 60

else:
curr = self.canvas.find_closest(s_x, s_y)[0]
if curr in self.reuse_list:

,
fill="green")
self.write_text("Correct! Cell {} is a co
cell.".format(
hexagon.tags))
if self.curr_count == len(self.reuse_list) - 1:
self.write_text("Great! Press Shift-R to
restart")
self.show_lines()
self.curr_count += 1

else:
self.write_text("Incorrect! Cell {} is not a co
cell.".format(
hexagon.tags))
self.canvas.itemconfigure(hexagon.tags, fill="red")

if __name__ == '__main__':
print(
"""Enter i & j values. common (i,j) values are:
(1,0), (1,1), (2,0), (2,1), (3,0), (2,2)"""
)
i = int(input("Enter i: "))
j = int(input("Enter j: "))
if i == 0 and j == 0:
raise ValueError("i & j both cannot be zero")
elif j > i:
raise ValueError("value of j cannot be greater than i")
else:
N = (i**2 + i * j + j**2)
print("N is {}".format(N))
freqreuse = FrequencyReuse(cluster_size=N)
freqreuse.mainloop()

OUTPUT:

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603


CONCLUSION:

Thus the frequency reuse has been studied..

VPPCOE&VA-DM-COMP-FF-06

TE COMP Subject: Mobile Computing Lab Subject Code: CSL603

You might also like