JAVA 18
MainActivity.java Guest on 11th October 2020 03:48:44 PM
  1. package com.example.android.mapdemo;
  2.  
  3. import android.content.Context;
  4. import android.content.pm.PackageManager;
  5. import android.location.Criteria;
  6. import android.location.Location;
  7. import android.location.LocationListener;
  8. import android.location.LocationManager;
  9. import android.os.AsyncTask;
  10. import android.support.annotation.NonNull;
  11. import android.support.v4.app.ActivityCompat;
  12. import android.support.v7.app.AppCompatActivity;
  13. import android.os.Bundle;
  14. import android.Manifest;
  15. import android.util.Log;
  16. import android.view.View;
  17. import android.widget.Button;
  18. import android.widget.Toast;
  19.  
  20. import com.google.android.gms.maps.CameraUpdateFactory;
  21. import com.google.android.gms.maps.GoogleMap;
  22. import com.google.android.gms.maps.OnMapReadyCallback;
  23. import com.google.android.gms.maps.SupportMapFragment;
  24. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  25. import com.google.android.gms.maps.model.LatLng;
  26. import com.google.android.gms.maps.model.LatLngBounds;
  27. import com.google.android.gms.maps.model.Marker;
  28. import com.google.android.gms.maps.model.MarkerOptions;
  29.  
  30. import org.json.JSONException;
  31. import org.json.JSONObject;
  32.  
  33. import java.io.BufferedInputStream;
  34. import java.io.BufferedOutputStream;
  35. import java.io.BufferedReader;
  36. import java.io.IOException;
  37. import java.io.InputStream;
  38. import java.io.InputStreamReader;
  39. import java.io.OutputStream;
  40. import java.net.HttpURLConnection;
  41. import java.net.URL;
  42.  
  43. public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener{
  44.  
  45.     private static final String SERVER_LAT_KEY = "lat";
  46.     private static final String SERVER_LNG_KEY = "lng";
  47.     private static final int MY_PERMISSIONS_REQUEST = 301;
  48.     private GoogleMap map;
  49.     private Marker own;
  50.     private Marker server;
  51.     private boolean zoomedOut = true;
  52.     private LatLng current;
  53.     private Button send;
  54.     private Button receive;
  55.  
  56.  
  57.     OnReceivedFromServer recvTask;
  58.     SendToServer sendTask;
  59.  
  60.     @Override
  61.     protected void onCreate(Bundle savedInstanceState) {
  62.         super.onCreate(savedInstanceState);
  63.         setContentView(R.layout.activity_main);
  64.         requestPermissions();
  65.         send = (Button) findViewById(R.id.send);
  66.         receive = (Button) findViewById(R.id.receive);
  67.         send.setEnabled(false);
  68.         receive.setEnabled(false);
  69.         send.setOnClickListener(new View.OnClickListener() {
  70.             @Override
  71.             public void onClick(View v) {
  72.                 // Either you are sending your location to the server or you are receiving
  73.                 // location updates from the server. So destroy the recvTask if 'send' is clicked
  74.                 // and vice-versa.
  75.                 if (sendTask == null) {
  76.                     if (recvTask != null) {
  77.                         recvTask.cancel(true);
  78.                         recvTask = null;
  79.                     }
  80.                     sendTask = new SendToServer();
  81.                     sendTask.execute();
  82.                 }
  83.             }
  84.         });
  85.         receive.setOnClickListener(new View.OnClickListener() {
  86.             @Override
  87.             public void onClick(View v) {
  88.                 if (recvTask == null) {
  89.                     if (sendTask != null) {
  90.                         sendTask.cancel(true);
  91.                         sendTask = null;
  92.                     }
  93.                     recvTask = new OnReceivedFromServer();
  94.                     recvTask.execute();
  95.                 }
  96.             }
  97.         });
  98.         setupMap();
  99.     }
  100.  
  101.     // The Google Map is added programmatically and a container for it is declared in the
  102.     // activity.xml. There are other ways to do this.
  103.     private void setupMap(){
  104.         if (map == null) {
  105.             SupportMapFragment mapFrag = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
  106.             mapFrag.getMapAsync(this);
  107.             if (map != null) {
  108.                 map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  109.             }
  110.         }
  111.     }
  112.  
  113.     // You received a GoogleMap object.
  114.     // Experiment with cooler looking map types that MAP_TYPE_NORMAL.
  115.     @Override
  116.     public void onMapReady(GoogleMap googleMap) {
  117.         map = googleMap;
  118.         map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  119.         send.setEnabled(true);
  120.         receive.setEnabled(true);
  121.         getLocation();
  122.     }
  123.  
  124.     public void requestPermissions(){
  125.         // Here, thisActivity is the current activity
  126.         if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
  127.                 != PackageManager.PERMISSION_GRANTED ||
  128.                 checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
  129.                 != PackageManager.PERMISSION_GRANTED ||
  130.                 checkSelfPermission(Manifest.permission.INTERNET)
  131.                         != PackageManager.PERMISSION_GRANTED) {
  132.  
  133.                 ActivityCompat.requestPermissions(this,
  134.                         new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
  135.                                 Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET},
  136.                         MY_PERMISSIONS_REQUEST);
  137.         }
  138.  
  139.     }
  140.  
  141.     @Override
  142.     public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
  143.         switch (requestCode) {
  144.             case MY_PERMISSIONS_REQUEST: {
  145.                 // If request is cancelled, the result arrays are empty.
  146.                 if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
  147.                         grantResults[1] == PackageManager.PERMISSION_GRANTED &&
  148.                         grantResults[2] == PackageManager.PERMISSION_GRANTED)) {
  149.                     // permissions not obtained
  150.                     Toast.makeText(this,"failed request permission!", Toast.LENGTH_SHORT).show();
  151.                 }
  152.             }
  153.         }
  154.     }
  155.  
  156.     // You NEED to first check for location permissions before using the location.
  157.     // Make sure you declare the corresponding permission in your manifest.
  158.     private void getLocation() {
  159.         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  160.                 == PackageManager.PERMISSION_GRANTED) {
  161.             Criteria criteria = getCriteria();
  162.             String provider;
  163.             LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  164.  
  165.             if (locationManager != null) {
  166.                 provider = locationManager.getBestProvider(criteria, true);
  167.                 Location l = locationManager.getLastKnownLocation(provider);
  168.                 if(l!=null){
  169.                     updateWithNewLocation(l);
  170.                 }
  171.                 locationManager.requestLocationUpdates(provider, 0, 0, this);
  172.             }
  173.         }
  174.     }
  175.  
  176.     // Application criteria for selecting a location provider. See line 158 "getBestProvider"
  177.     // https://developer.android.com/reference/android/location/Criteria.html
  178.     private Criteria getCriteria(){
  179.         Criteria criteria = new Criteria();
  180.         criteria.setAccuracy(Criteria.ACCURACY_FINE);
  181.         criteria.setPowerRequirement(Criteria.POWER_LOW);
  182.         criteria.setAltitudeRequired(true);
  183.         criteria.setBearingRequired(false);
  184.         criteria.setSpeedRequired(true);
  185.         criteria.setCostAllowed(true);
  186.         return criteria;
  187.     }
  188.  
  189.     // Put the marker at given location and zoom into the location
  190.     private void updateWithNewLocation(Location location) {
  191.         if (location != null) {
  192.             LatLng l = fromLocationToLatLng(location);
  193.             current = l;
  194.             drawMarker(l, false);
  195.             moveToCurrentLocation(l);
  196.         }
  197.     }
  198.  
  199.     // Remove old marker and place new marker.
  200.     private void drawMarker(LatLng l, boolean serverLoc){
  201.         if(serverLoc) {
  202.             if (server != null)
  203.                 server.remove();
  204.             server = map.addMarker(new MarkerOptions().position(l).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
  205.         } else{
  206.             if (own != null)
  207.                 own.remove();
  208.             own = map.addMarker(new MarkerOptions().position(l).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
  209.         }
  210.     }
  211.  
  212.     // LatLng stores the "location" as two doubles, latitude and longitude.
  213.     public static LatLng fromLocationToLatLng(Location location){
  214.         return new LatLng(location.getLatitude(), location.getLongitude());
  215.     }
  216.  
  217.     @Override
  218.     public void onLocationChanged(Location location) {
  219.         // Called whenever the location is changed.
  220.         updateWithNewLocation(location);
  221.     }
  222.  
  223.     @Override
  224.     public void onStatusChanged(String provider, int status, Bundle extras) {
  225.         // Called when the provider status changes.
  226.     }
  227.  
  228.     @Override
  229.     public void onProviderEnabled(String provider) {
  230.  
  231.     }
  232.  
  233.     @Override
  234.     public void onProviderDisabled(String provider) {
  235.  
  236.     }
  237.  
  238.     // The AsyncTask that receives the latitude and longitude from the server and puts a marker at that location.
  239.     private class OnReceivedFromServer extends AsyncTask<Void, Double, Void> {
  240.  
  241.         @Override
  242.         protected void onPreExecute() {
  243.             super.onPreExecute();
  244.         }
  245.  
  246.         @Override
  247.         protected void onProgressUpdate(Double... values) {
  248.             super.onProgressUpdate(values);
  249.             if(values.length >=2 ){
  250.                 drawMarker(new LatLng(values[0], values[1]), true);
  251.                 moveToCurrentLocation(new LatLng(values[0], values[1]));
  252.             }
  253.         }
  254.  
  255.         @Override
  256.         protected Void doInBackground(Void... arg0) {
  257.             String res;
  258.             // Keep receiving the updated location from the server every 2 seconds.
  259.             while (!isCancelled()) {
  260.                 try {
  261.                     URL url = new URL("http://cs65.cs.dartmouth.edu/profile.pl?name=demo&password=1234" );
  262.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  263.                     InputStream in = conn.getInputStream();
  264.                     res = readStream(in);
  265.                     JSONObject o = new JSONObject(res);
  266.                     if(o != null){
  267.                         publishProgress(o.getDouble(SERVER_LAT_KEY),o.getDouble(SERVER_LNG_KEY));
  268.                         //publishProgress(43.44,44.33); // to test multiple markers
  269.                     }
  270.                     Thread.sleep(2000);
  271.                 } catch (Exception e) {
  272.                     e.printStackTrace();
  273.                 }
  274.  
  275.             }
  276.             return null;
  277.         }
  278.  
  279.         @Override
  280.         protected void onCancelled() {
  281.             //when cancelled, simply stop
  282.         }
  283.  
  284.     }
  285.  
  286.     private String readStream(InputStream in) throws IOException {
  287.         BufferedReader r = new BufferedReader(new InputStreamReader(in));
  288.         StringBuilder total = new StringBuilder();
  289.         String line;
  290.         while ((line = r.readLine()) != null) {
  291.             total.append(line).append('\n');
  292.         }
  293.         return total.toString();
  294.     }
  295.  
  296.     // AsyncTask to send the sever location updates every 2s.
  297.     private class SendToServer extends AsyncTask<Void, Double, Void> {
  298.  
  299.         @Override
  300.         protected void onPreExecute() {
  301.             super.onPreExecute();
  302.  
  303.         }
  304.  
  305.         @Override
  306.         protected void onProgressUpdate(Double... values) {
  307.             super.onProgressUpdate(values);
  308.             if(values.length >=2 ){
  309.                 drawMarker(new LatLng(values[0], values[1]), true);
  310.                 moveToCurrentLocation(new LatLng(values[0], values[1]));
  311.                 String text = String.valueOf(values[0]).concat(String.valueOf(values[1]));
  312.                 Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
  313.             }
  314.         }
  315.  
  316.         @Override
  317.         protected Void doInBackground(Void... arg0) {
  318.             String res = null, req = null;
  319.             while (!isCancelled()) {
  320.                 // Right now, we just post the latitude and longitude as POST parameters.
  321.                 // The server echoes them back to anyone who wants to receive the location.
  322.                 try {
  323.                     // the 'current' global variable stores the last known location.
  324.                     // it is updated in onLocationChanged.
  325.                     if(current != null) {
  326.                         URL url = new URL("http://cs65.cs.dartmouth.edu/profile.pl");
  327.                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  328.                         req = buildJSONReq(current);
  329.                         conn.setDoOutput(true);
  330.                         conn.setRequestMethod("POST");
  331.                         conn.setRequestProperty("Content-Type", "application/json");
  332.                         conn.setRequestProperty("Accept-Encoding", "identity");
  333.                         conn.setFixedLengthStreamingMode(req.length());
  334.                         OutputStream out = new BufferedOutputStream(conn.getOutputStream());
  335.                         out.write(req.getBytes());
  336.                         out.flush();
  337.                         out.close();
  338.                         // after sending our location to the server, also reflect it on the screen.
  339.                         // might be redundant since we update our location every time the
  340.                         // onLocationChanged() callback is called.
  341.                         publishProgress(current.latitude,current.longitude);
  342.                     }
  343.                     Thread.sleep(2000);
  344.                 } catch (Exception e) {
  345.                     e.printStackTrace();
  346.                 }
  347.             }
  348.             return null;
  349.         }
  350.  
  351.         @Override
  352.         protected void onCancelled() {
  353.             //when cancelled, simply stop
  354.         }
  355.  
  356.         private String buildJSONReq(LatLng location){
  357.             JSONObject o = new JSONObject();
  358.             if(location != null){
  359.                 try {
  360.                     o.put("name", "demo");
  361.                     o.put(SERVER_LAT_KEY, location.latitude);
  362.                     o.put(SERVER_LNG_KEY, location.longitude);
  363.                     o.put("password", "1234");
  364.                 }
  365.                 catch( JSONException e){
  366.                     Log.d("JSON", e.toString());
  367.                 }
  368.             }
  369.             return o.toString();
  370.         }
  371.  
  372.     }
  373.  
  374.     // If the given location is visible on the mobile screen (visible region), do not zoom in.
  375.     // zoomedOut is a variable that is initialized to True and ensures that the zoom level is set.
  376.     private void moveToCurrentLocation(LatLng currentLocation)
  377.     {
  378.         LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds;
  379.         if(!bounds.contains(currentLocation) || zoomedOut ){
  380.             map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,15));
  381.             // Zoom in, animating the camera.
  382.             map.animateCamera(CameraUpdateFactory.zoomIn());
  383.             // Zoom out to zoom level 10, animating with a duration of 1 second.
  384.             map.animateCamera(CameraUpdateFactory.zoomTo(15), 1000, null);
  385.             zoomedOut = false;
  386.         }
  387.     }
  388.  
  389. }

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.