Where are you?
  • My Project
  • Blog
  • About Me
  • Source Code & Downloads
    • Login.java
    • MainActivity.java
    • MapsActivity.java
    • Tab1.java
    • Tab2.java
    • Tab3.java
mapsactivity.java
File Size: 15 kb
File Type: java
Download File

package c.test2;

import android.Manifest;
import android.app.AlertDialog;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;

/*********************************************************************************************
 * MapsActivity Class/Activity
 * This activity opens a map, and based off of the personal users location it places a marker
        for the user as well as a marker for the person that the user is looking at. It grabs
        the other user's (them) location from the location file through an asyncTask. Then when
        it calculates the position of the user (me) it calls a php script and writes it to the
        location.txt file on compsci02 server.
 * A lot of this activity is taken from a treehouse guide to location on androids. The writer
        of the guide is Ben Jakuben. the functions that are from the guide are onResume, onPause,
        setUpMapIfNeeded, setUpMap, onConnected, onConnectSuspended, onConnectFailed, and
        onLocationChanged. as well as the GoogleApiClient, LocationRequest, and GoogleMap objects.
 *********************************************************************************************/
public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private String me;
    private String them;

    public static final String TAG = MapsActivity.class.getSimpleName();

    /*
     * Define a request code to send to Google Play services
     * This code is returned in Activity.onActivityResult
     */
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

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

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        Bundle extras = getIntent().getExtras();

        me = extras.getString("user");
        them = extras.getString("otheruser");

        new ConnectTask().execute("http://compsci02.snc.edu/cs460/2016/lewicj/WhereAreYou/locations.txt", them);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }

    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("I am here!");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //added writeable connection to server file to write current location to file
        new WriteConnectTask().execute(Double.toString(currentLatitude),Double.toString(currentLongitude));
    }

    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }

    /******************************************************************************************
     * ConnectTask
     * This AsyncTask uses an HttpURLConnection to contact the compsci02 server and read the
            data from the location.txt file.
     * Has background function and OnPostExecute function
     *****************************************************************************************/
    public class ConnectTask extends AsyncTask<String, String, String>
    {
        /**************************************************************
         * doInBackground
         * Creates a connection with the file on the server and reads
                each line one by one until the end of the file or
                until it reaches the correct user.
         **************************************************************/
        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            String user[]; //find user by reading line in file
            String currentuser = params[1]; //user in group that is currently being checked

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                String line = "";

                while ((line = reader.readLine()) != null)
                {
                    user = line.split(";");
                    if(Objects.equals(currentuser, user[2]))
                    {
                        return line;
                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return "error";
        }

        /**************************************************************
         * onPostExecute
         * This function makes sure the user returned from the file's
                location is not hidden and if not then it creates a
                map marker, otherwise it lets the user know that the
                persons location is hidden.
         **************************************************************/
        @Override
        protected void onPostExecute(String line) {
            super.onPostExecute(line);
            if(!Objects.equals(line, "error")) {
                String loc[];
                loc = line.split(";");

                if(Objects.equals(loc[3],"1")) {
                    double currentLatitude = Double.parseDouble(loc[0]);
                    double currentLongitude = Double.parseDouble(loc[1]);

                    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

                    MarkerOptions options = new MarkerOptions()
                            .position(latLng)
                            .title(loc[2])
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                    mMap.addMarker(options);
                }
                else {
                    Toast.makeText(MapsActivity.this, "User has turned off their location.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /******************************************************************************************
     * WriteConnectTask
     * This AsyncTask uses an HttpURLConnection to contact the compsci02 server and execute
            a php script which then writes to the location.txt file.
     * Has background function and OnPostExecute function
     *****************************************************************************************/
    public class WriteConnectTask extends AsyncTask<String, String, String>
    {
        /**************************************************************
         * doInBackground
         * Creates a connection with the file on the server and executes
                the location script with the parameters sent to it.
         **************************************************************/
        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection connection = null;
            String phpscript = "http://compsci02.snc.edu/cs460/2016/lewicj/WhereAreYou/writelocation.php?lat="+params[0]+"&long="+params[1]+"&user="+me;

            try {
                URL url = new URL(phpscript);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("GET");

                InputStream in = connection.getInputStream();

                return "success";

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }

            return "error";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }
}
Create a free web site with Weebly
  • My Project
  • Blog
  • About Me
  • Source Code & Downloads
    • Login.java
    • MainActivity.java
    • MapsActivity.java
    • Tab1.java
    • Tab2.java
    • Tab3.java