You are on page 1of 52

PRIYA S.

UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 1
PROGRAM:
GPSTracker.java
package com.example.priyasharma.locationbasedapp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status


boolean isGPSEnabled = false;

// flag for network status


boolean isNetworkEnabled = false;

// flag for GPS status


boolean canGetLocation = false;

Location location; // location


double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager


protected LocationManager locationManager;

1
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

public GPSTracker(Context context) {


this.mContext = context;
getLocation();
}

@SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

// getting GPS status


isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status


isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {


// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

// if GPS Enabled get lat/long using GPS Services


if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("GPS Enabled", "GPS Enabled");


if (locationManager != null) {
location = locationManager

2
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
}

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */

public void stopUsingGPS(){


if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
* */

public double getLatitude(){


if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */

public double getLongitude(){


if(location != null){
longitude = location.getLongitude();
}

3
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */

public boolean canGetLocation() {


return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */

public void showSettingsAlert(){


AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title


alertDialog.setTitle("GPS is settings");

// Setting Dialog Message


alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

// On pressing Settings button


alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button


alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message


alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override

4
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

public void onProviderDisabled(String provider) {


}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

MainActivity.java
package com.example.priyasharma.locationbasedapp;

import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.app.Activity;
import android.Manifest;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

// GPSTracker class
GPSTracker gps;

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

try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]{mPermission},

5
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

REQUEST_CODE_PERMISSION);

// If any permission above not allowed by user, this condition will


//execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}

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

// show location button click event


btnShowLocation.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);

// check if GPS enabled


if(gps.canGetLocation()){

double latitude = gps.getLatitude();


double longitude = gps.getLongitude();

// \n is for new line


Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}

}
});
}
}

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.example.priyasharma.locationbasedapp.MainActivity">

<TextView

6
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="29dp"
android:layout_marginBottom="118dp"
android:layout_marginTop="82dp"
android:text="Location based app"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.175" />

<Button
android:id="@+id/button"
android:layout_width="113dp"
android:layout_height="56dp"
android:layout_marginBottom="225dp"
android:text="Get your location"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

</android.support.constraint.ConstraintLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.priyasharma.locationbasedapp">

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


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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


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

7
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

OUTPUT:

8
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 2
PROGRAM:
GPSTracker.java
package com.example.priyasharma.locationbasedapp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status


boolean isGPSEnabled = false;

// flag for network status


boolean isNetworkEnabled = false;

// flag for GPS status


boolean canGetLocation = false;

Location location; // location


double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager


protected LocationManager locationManager;

9
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

public GPSTracker(Context context) {


this.mContext = context;
getLocation();
}

@SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

// getting GPS status


isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status


isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {


// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

// if GPS Enabled get lat/long using GPS Services


if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("GPS Enabled", "GPS Enabled");


if (locationManager != null) {
location = locationManager

10
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
}

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */

public void stopUsingGPS(){


if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
* */

public double getLatitude(){


if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}

/**
* Function to get longitude
* */

public double getLongitude(){


if(location != null){
longitude = location.getLongitude();
}

11
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */

public boolean canGetLocation() {


return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */

public void showSettingsAlert(){


AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title


alertDialog.setTitle("GPS is settings");

// Setting Dialog Message


alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

// On pressing Settings button


alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// on pressing cancel button


alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message


alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override

12
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

public void onProviderDisabled(String provider) {


}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

MainActivity.java
package com.example.priyasharma.locationbasedapp;

import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.app.Activity;
import android.Manifest;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

// GPSTracker class
GPSTracker gps;

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

try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]{mPermission},

13
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

REQUEST_CODE_PERMISSION);

// If any permission above not allowed by user, this condition will


//execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}

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

// show location button click event


btnShowLocation.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);

// check if GPS enabled


if(gps.canGetLocation()){

double latitude = gps.getLatitude();


double longitude = gps.getLongitude();

// \n is for new line


Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}

}
});
}
}

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.example.priyasharma.locationbasedapp.MainActivity">

<TextView

14
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="29dp"
android:layout_marginBottom="118dp"
android:layout_marginTop="82dp"
android:text="Location based app"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.175" />

<Button
android:id="@+id/button"
android:layout_width="113dp"
android:layout_height="56dp"
android:layout_marginBottom="225dp"
android:text="Get your location"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

</android.support.constraint.ConstraintLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.priyasharma.locationbasedapp">

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


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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


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

15
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

OUTPUT:

16
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 3
STEPS:
1. Start Android Studio and create new project with empty activity. Go to Tools>Firebase.

2. Select Cloud Messaging> Set up Firebase cloud messaging.

17
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

3. Follow all the steps as given.

18
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

19
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

20
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

4. Create a new java class named FirebaseIDService which must extend FirebaseInstanceIdService

FirebaseIDService.java
package com.example.priyasharma.messaging;

import com.google.firebase.iid.FirebaseInstanceIdService;
import com.google.firebase.iid.FirebaseInstanceId;
import android.util.Log;

/**
* Created by Priya Sharma on 22-12-2018.
*/

public class FirebaseIDService extends FirebaseInstanceIdService {

private static final String TAG = "FirebaseIDService";

@Override
public void onTokenRefresh() {
// Get updated InstanceID token.

21
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

String refreshedToken = FirebaseInstanceId.getInstance().getToken();


Log.d(TAG, "Refreshed token: " + refreshedToken);

// If you want to send messages to this application instance or


// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token){

}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.priyasharma.messaging">

<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>

<service
android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

</application>
</manifest>

MainActivity.java

package com.example.priyasharma.messaging;

import android.support.v7.app.AppCompatActivity;

22
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

5. Run the app and note the refreshed token obtained in the output. Go to Firebase console, click on “send
your first message” and create a notification. Also, provide the token generated in the android logcat.

Refreshed token should be as follows:

23
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

24
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

As soon as the notification is sent, drag down the notification panel of your android device or emulator. The
notification is seen as below:

25
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

OUTPUT:

26
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 4
Connect to firebase and set up your android project using appropriate settings. Note down your
“senderID” from the firebase console (of your app).

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.example.priyasharma.upstreammessaging.MainActivity">

<EditText
android:id="@+id/editKey1"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="137dp"
android:layout_marginEnd="41dp"
android:layout_marginStart="39dp"
android:layout_marginTop="69dp"
android:ems="10"
android:hint="key1"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="@+id/sendBtn"
app:layout_constraintEnd_toStartOf="@+id/editVal1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="41dp"
android:layout_marginLeft="39dp" />

<EditText
android:id="@+id/editKey2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="322dp"
android:layout_marginEnd="29dp"
android:layout_marginStart="39dp"
android:ems="10"
android:hint="key2"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/editVal2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editKey1"
android:layout_marginRight="29dp"
android:layout_marginLeft="39dp" />

<EditText

27
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

android:id="@+id/editVal1"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="27dp"
android:layout_marginEnd="77dp"
android:layout_marginTop="69dp"
android:ems="10"
android:hint="value1"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="@+id/editVal2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/editKey1"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="77dp" />

<EditText
android:id="@+id/editVal2"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="325dp"
android:layout_marginEnd="75dp"
android:ems="10"
android:hint="value2"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/editKey2"
app:layout_constraintTop_toBottomOf="@+id/editVal1"
android:layout_marginRight="75dp" />

<Button
android:id="@+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="211dp"
android:text="SEND MESSAGE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editKey1"
tools:ignore="MissingConstraints" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.example.priyasharma.upstreammessaging;

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

28
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Map;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

private Button button;


private EditText editText1;
private EditText editText2;
private EditText editText3;
private EditText editText4;

private final String TAG="JSA-FCM";


private final String SENDER_ID="542714781324";
private Random random=new Random();

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

editText1=(EditText)findViewById(R.id.editKey1);
editText2=(EditText)findViewById(R.id.editKey2);
editText3=(EditText)findViewById(R.id.editVal1);
editText4=(EditText)findViewById(R.id.editVal2);
button=(Button)findViewById(R.id.sendBtn);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FirebaseMessaging fm=FirebaseMessaging.getInstance();
RemoteMessage msg=new RemoteMessage.Builder(SENDER_ID+"@gcm.googleapis.com")
.setMessageId(Integer.toString(random.nextInt(9999)))
.addData(editText1.getText().toString(),editText3.getText().toString())
.addData(editText2.getText().toString(),editText4.getText().toString())
.build();

if(!msg.getData().isEmpty()){
Log.e(TAG,"UpstreamData:"+msg.getData());
}

if(!msg.getMessageId().isEmpty()){
Log.e(TAG,"UpstreamMessageId:"+msg.getMessageId());
}

29
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

fm.send(msg);
}
});
}
}
FCMClass.java

package com.example.priyasharma.upstreammessaging;

import com.google.firebase.messaging.FirebaseMessagingService;
import android.util.Log;

/**
* Created by Priya Sharma on 23-12-2018.
*/

public class FCMClass extends FirebaseMessagingService {

private final String TAG="JSA-FCM";

public void onMessageSent(String msgId){


Log.e(TAG,"onMessageSent:"+msgId);
}

public void onSendError(String msgId,Exception e){


Log.e(TAG,"onSendError:"+msgId);
Log.e(TAG,"Exception:"+e);
}
}

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.priyasharma.upstreammessaging">

<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>

30
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

</activity>

<service
android:name=".FCMClass">
<intent-filter>
<action
android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>

Build.gradle (app)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

repositories {
google()
jcenter()
maven{
url "https://maven.google.com"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'

// NOTE: Do not place your application dependencies here; they belong


// in the individual module build.gradle files
classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {


delete rootProject.buildDir
}

Send the message in key-value pair from your app as follows:

31
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

32
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 6
PROGRAM:
MainActivity.java
package com.example.priyasharma.gcmmanagerdemo;

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

import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.OneoffTask;
import com.google.android.gms.gcm.PeriodicTask;
import com.google.android.gms.gcm.Task;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

private static final String TAG="MainActivity";


public static final String TAG_TASK_PERIODIC="periodic task";

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

GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(this);

PeriodicTask periodicTask=new PeriodicTask.Builder()


.setService(MyTaskService.class)
.setPeriod(60)
.setFlex(30)
.setRequiresCharging(true)
.setTag(TAG_TASK_PERIODIC)
.build();

mGcmNetworkManager.schedule(periodicTask);

}
}

MyTaskService.java
package com.example.priyasharma.gcmmanagerdemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

33
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.GcmTaskService;
import com.google.android.gms.gcm.TaskParams;

public class MyTaskService extends GcmTaskService {

private static final String TAG = "MyTaskService";

public MyTaskService() {
}

@Override
public int onRunTask(TaskParams taskParams) {
Log.i(TAG, "onRunTask:" + taskParams.getTag());

String tag = taskParams.getTag();

if (MainActivity.TAG_TASK_PERIODIC.equals(tag)) {
Log.i(TAG, MainActivity.TAG_TASK_PERIODIC);
return GcmNetworkManager.RESULT_SUCCESS;
}
return 0;
}
}

build.gradle(app)
apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.priyasharma.gcmmanagerdemo"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

34
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'
compile 'com.android.support:support-core-utils:26.1.0'
//noinspection GradleCompatible
compile 'com.google.android.gms:play-services-gcm:8.1.0'
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.priyasharma.gcmmanagerdemo">

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


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

<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>

<service
android:name=".MyTaskService"
android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.gcm.ACTION_TASK_READY"/>
</intent-filter>
</service>
</application>
</manifest>

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"

35
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.priyasharma.gcmmanagerdemo.MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GCM Manager Practical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.448"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.071" />

</android.support.constraint.ConstraintLayout>

OUTPUT:

36
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 7
STEPS:
1. Download and unzip OpenGTS_2.6.5 to “C:\OpenGTS_2.6.5”.
2. Download XAMPP server.
3. Download MySQL-connector-java jar file.
4. Download JDK (if not already present).
5. Download Apache Ant build tool.
6. Copy and paste MySQL-connector-java jar file in the JDK and JRE directories.
7. Set the following environment variables by going to Control Panel>System>Advanced System
settings>Environment variables.
 JAVA_HOME- C:\Program Files\Java\jdk1.8.0_65
 GTS_HOME- C:\OpenGTS_2.6.5
 ANT_HOME- C:\apache-ant-1.10.5
 CATALINA_HOME- C:\xampp\tomcat
8. Edit the following in the PATH variable
 C:\apache-ant-1.10.5\bin
 C:\Program Files\Java\jdk1.8.0_65\bin

Follow the steps below, after completing the above procedure:

37
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

38
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

39
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

OUTPUT:

40
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

41
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 9
PROGRAM:
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class MouseTrackerFrame extends JFrame
{
private JPanel mousePanel;
private JLabel statusBar;
public MouseTrackerFrame()
{
super("Demonstrating HCI using mouse events");
mousePanel=new JPanel();
mousePanel.setBackground(Color.WHITE);
add(mousePanel,BorderLayout.CENTER);

statusBar=new JLabel("Mouse oustide JPanel");


add(statusBar,BorderLayout.SOUTH);

MouseHandler handler = new MouseHandler();


mousePanel.addMouseListener(handler);
mousePanel.addMouseMotionListener(handler);
}
private class MouseHandler implements MouseListener,MouseMotionListener
{

42
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

public void mouseClicked(MouseEvent event)


{
statusBar.setText(String.format("Clicked at [%d, %d]",event.getX(),event.getY()));
}
public void mousePressed(MouseEvent event)
{
statusBar.setText(String.format("Pressed at [%d, %d]",event.getX(),event.getY()));
}
public void mouseReleased(MouseEvent event)
{
statusBar.setText(String.format("Released at [%d, %d]",event.getX(),event.getY()));
}
public void mouseEntered(MouseEvent event)
{
statusBar.setText(String.format("Mouse enters at [%d, %d]",event.getX(),event.getY()));
mousePanel.setBackground(Color.GREEN);
}
public void mouseExited(MouseEvent event)
{
statusBar.setText(String.format("Mouse oustide JPanel"));
mousePanel.setBackground(Color.WHITE);
}
public void mouseDragged(MouseEvent event)
{
statusBar.setText(String.format("Dragged at [%d, %d]",event.getX(),event.getY()));
}
public void mouseMoved(MouseEvent event)
{
statusBar.setText(String.format("Moved at [%d, %d]",event.getX(),event.getY()));
}

43
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

}
public static void main(String[] args )
{
MouseTrackerFrame mouseTrackerFrame = new MouseTrackerFrame();
mouseTrackerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mouseTrackerFrame.setSize(300,100); // set frame size
mouseTrackerFrame.setVisible(true); // display frame 13
} //end main
} // end class

OUTPUT:

44
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

45
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

46
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

47
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

PRACTICAL 10
STEPS:
Start Netbeans. Create new Java Card > Classic Applet Project. Give an appropriate name and start the project
with the default configurations.

48
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

49
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

CODE:
package classicapplet1;
import javacard.framework.*;
public class JavaCardApplet extends Applet {

/**
* Installs this applet.
*
* @param bArray
* the array containing installation parameters
* @param bOffset
* the starting offset in bArray
* @param bLength

50
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

* the length in bytes of the parameter data in bArray


*/
public static void install(byte[] bArray, short bOffset, byte bLength) {
new JavaCardApplet();
}

/**
* Only this class's install method should create the applet object.
*/
protected JavaCardApplet() {
register();
}

/**
* Processes an incoming APDU.
*
* @see APDU
* @param apdu
* the incoming APDU
*/
public void process(APDU apdu) {
//Insert your code here
}
}

51
PRIYA S. UBIQUITOUS COMPUTING ROLL NO: 38

OUTPUT:

52

You might also like