title: Android Studio JAVA: Send SMS of user's current location ;
body: <p>I am Trying to Build an app where user can show their location and send an SMS to nearby hospital.
  I am new to android studio and everything about it, but I quite made a progress with it.</p>
  <p>I have 2 XML files, but I'll provide the JAVA CLASSES first</p>
  <p>MapActivity.java</p>
  <pre><code>package maptesting.app;
  
  import androidx.annotation.NonNull;
  import androidx.annotation.Nullable;
  import androidx.core.app.ActivityCompat;
  import androidx.core.content.ContextCompat;
  import androidx.fragment.app.FragmentActivity;
  
  import android.Manifest;
  import android.content.Context;
  import android.content.Intent;
  import android.content.pm.PackageManager;
  import android.graphics.Color;
  import android.location.Address;
  import android.location.Criteria;
  import android.location.Geocoder;
  import android.location.Location;
  import android.location.LocationManager;
  import android.net.ConnectivityManager;
  import android.net.NetworkInfo;
  import android.os.Build;
  import android.os.Bundle;
  import android.os.Looper;
  import android.telephony.SmsManager;
  import android.util.Log;
  import android.view.View;
  import android.widget.EditText;
  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.FusedLocationProviderClient;
  import com.google.android.gms.location.LocationCallback;
  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.MapView;
  import com.google.android.gms.maps.OnMapReadyCallback;
  import com.google.android.gms.maps.SupportMapFragment;
  import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  import com.google.android.gms.maps.model.CircleOptions;
  import com.google.android.gms.maps.model.LatLng;
  import com.google.android.gms.maps.model.Marker;
  import com.google.android.gms.maps.model.MarkerOptions;
  
  import java.io.IOException;
  import java.util.List;
  
  import maptesting.app.databinding.ActivityMapBinding;
  
  public class MapActivity&lt;mapView&gt; extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
          GoogleApiClient.OnConnectionFailedListener, LocationListener {
      private ActivityMapBinding binding;
      private View mapView;
      private GoogleMap mMap;
      private GoogleApiClient client;
      private LocationRequest locationRequest;
      private Location lastlocation;
      private LocationManager locationManager;
      private Marker currentLocationmMarker;
      public static final int REQUEST_LOCATION_CODE = 99;
      int PROXIMITY_RADIUS = 15000;
      double latitude, longitude;
      private int LOCATION_MIN_DISTANCE = 20;
      private int LOCATION_MIN_TIME = 4000;
      private boolean requestingLocationUpdates;
  
      //NEW
      private int FINE_LOCATION_REQUEST_CODE = 10001;
      private float Geofence_Radius = 4000;
      private Object CircleOptions;
  
      //NEW SMS
      private LocationListener locationListener;
      private final long mTime = 1000;
      private final long mDist = 5;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
  
          binding = ActivityMapBinding.inflate(getLayoutInflater());
          setContentView(binding.getRoot());
  
          if (!isConnectedToNetwork()) {
              Toast.makeText(this, &quot;Turn on mobile data or Wifi&quot;, Toast.LENGTH_LONG).show();
              finish();
          }
          if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {
              checkLocationPermission();
          }
  
          // Obtain the SupportMapFragment and get notified when the map is ready to be used.
          SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
          mapView = mapFragment.getView();
          mapFragment.getMapAsync(this);
      }
  
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
          super.onRequestPermissionsResult(requestCode, permissions, grantResults);
          switch (requestCode) {
              case REQUEST_LOCATION_CODE:
                  if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                          if (client == null) {
                              buildGoogleApiClient();
                          }
                          mMap.setMyLocationEnabled(true);
                      }
  
                      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                          mMap.setMyLocationEnabled(true);
  
                          Intent intent = getIntent();
                          finish();
                          startActivity(intent);
                      }
  
                  } else {
                      Toast.makeText(this, &quot;Location Permission Denied&quot;, Toast.LENGTH_LONG).show();
                  }
          }
      }
  
      @Override
      public void onMapReady(@NonNull GoogleMap googleMap) {
          mMap = googleMap;
  
  
          if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
              buildGoogleApiClient();
  
              mMap.setMyLocationEnabled(true);
  
              // View locationButton = ((View) mapView.findViewById(Integer.parseInt(&quot;1&quot;)).getParent()).findViewById(Integer.parseInt(&quot;2&quot;));
              //locationButton.callOnClick();
          }
  
          //NEW INPUT (SMS)
          LatLng msgloc = new LatLng(lastlocation.getLatitude(), lastlocation.getLongitude());
          locationListener = new LocationListener()
          {
              @Override
              public void onLocationChanged(@NonNull Location location)
              {
                  try
                  {
                      String phoneNum = &quot;09553625915&quot;;
                      String loc = String.valueOf(msgloc);
  
                      String message = &quot;Location = &quot; + msgloc;
  
                      SmsManager smsManager = SmsManager.getDefault();
                      smsManager.sendTextMessage(phoneNum, null, message, null, null);
  
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                  }
              }
  
              public void onProviderEnabled(@NonNull String provider)
              {
  
              }
  
              public void onProviderDisabled(@NonNull String provider)
              {
  
              }
  
              public void onStatusChanged(String provider, int status, Bundle extras)
              {
  
              }
          };
  
          locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
          try
          {
              locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mTime, mDist,
                      (android.location.LocationListener) locationListener);
              locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, mTime, mDist,
                      (android.location.LocationListener) locationListener);
          }
          catch (SecurityException e)
          {
              e.printStackTrace();
          }
          //END NEW INPUT (SMS)
      }
  
      private void buildGoogleApiClient() {
          client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
          client.connect();
      }
  
      @Override
      public void onLocationChanged(@NonNull Location location)
      {
          latitude = location.getLatitude();
          longitude = location.getLongitude();
          lastlocation = location;
          if (currentLocationmMarker != null)
          {
              currentLocationmMarker.remove();
          }
          Log.d(&quot;lat = &quot;, &quot;&quot; + latitude);
          Log.d(&quot;lng = &quot;, &quot;&quot; + longitude);
          LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
          MarkerOptions markerOptions = new MarkerOptions();
          markerOptions.position(latLng);
          markerOptions.title(&quot;Current Location&quot;);
          AddCircle(latLng, Geofence_Radius);
          //markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
          //currentLocationmMarker = mMap.addMarker(markerOptions);
  
          if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; 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;
          }
          mMap.setMyLocationEnabled(true);
          mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
  
  
          //mMap.animateCamera(CameraUpdateFactory.zoomBy(2));
  
  
  
          //todo delete following lines
          Object[] dataTransfer = new Object[2];
          getNearbyPlacesData getNearbyPlacesData = new getNearbyPlacesData();
          String url = getUrl(latitude, longitude, &quot;hospital&quot;);
          dataTransfer[0] = mMap;
          dataTransfer[1] = url;
          getNearbyPlacesData.execute(dataTransfer);
          Toast.makeText(MapActivity.this, &quot;Showing Nearby Hospitals&quot;, Toast.LENGTH_SHORT).show();
          //todo end
  
          if (client != null) {
              LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
          }
      }
  
      private String getUrl(double latitude, double longitude, String nearbyPlace)
      {
  
          StringBuilder googlePlaceUrl = new StringBuilder(&quot;https://maps.googleapis.com/maps/api/place/nearbysearch/json?&quot;);
          googlePlaceUrl.append(&quot;location=&quot; + latitude + &quot;,&quot; + longitude);
          googlePlaceUrl.append(&quot;&amp;radius=&quot; + PROXIMITY_RADIUS);
          googlePlaceUrl.append(&quot;&amp;type=&quot; + nearbyPlace);
          googlePlaceUrl.append(&quot;&amp;sensor=true&quot;);
  
          //Todo: add your google api key here
          googlePlaceUrl.append(&quot;&amp;key=&quot; + &quot;YOUR_API_KEY&quot;);
  
          Log.d(&quot;MapsActivity&quot;, &quot;url = &quot; + googlePlaceUrl.toString());
  
          return googlePlaceUrl.toString();
      }
  
      @Override
      public void onConnected(@Nullable Bundle bundle) {
          locationRequest = new LocationRequest();
          locationRequest.setInterval(5);
          locationRequest.setFastestInterval(500);
          locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  
          // ORG
          if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
  
              LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
          }
      }
  
      private boolean checkLocationPermission()
      {
          if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)  != PackageManager.PERMISSION_GRANTED )
          {
  
              if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION))
              {
                  ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
              }
              else
              {
                  ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
              }
              return false;
          }
          else
          {
              return true;
          }
  
      }
  
      @Override
      public void onConnectionSuspended(int i) {
  
      }
  
      @Override
      public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  
      }
  
      private boolean isConnectedToNetwork() {
          ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  
          return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                  connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
      }
  
      // Add Circle
      private void AddCircle(LatLng latLng, float radius)
      {
          mMap.addCircle(new CircleOptions()
                  .center(latLng)
                  .radius(Geofence_Radius)
                  .strokeColor(Color.argb(50, 0, 0, 0))
                  .fillColor(Color.argb(13,0,0,0))
                  .strokeWidth(4));
      }
  </code></pre>
  <p>What I want to see if its possible to send the user's current location to another phone after I hit the button that will also show their current location in the map.</p>
  <p>I am willing to provide the source code if you kind sirs and ma'ams want to check my code.</p>
  <p>Thank you</p>