Home » Android » android – Get current location during app launch

android – Get current location during app launch

Posted by: admin June 15, 2020 Leave a comment

Questions:

Good Day!
I am working on an android app which monitors user location. I am using LocationManager to get users location, using the following method

public void onLocationChanged(Location theLocation) {}

Through the above method, whenever there was a user movement, I am receiving location coordinates.

But, now I am planning to get user’s location immediately after their app login. Is there any way through LocationManager through which I can manually get the location coordinates after my app launch?

How to&Answers:

Use this technique :

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

boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location location;

if(network_enabled){

   location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

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

In this case you even no need to on GPS only your mobile network will do.

Don’t forget to give the following permission in Manifest:

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

Answer:

Try This Code.Hope It will work

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class MainActivity extends Activity implements LocationListener {

private LocationManager locationManager;
private String provider;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
      } else {
        System.out.println("Location not avilable");
      }

}

protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, (LocationListener) this);
  }

  /* Remove the locationlistener updates when Activity is paused */
  @Override
  protected void onPause() {
    super.onPause();
    locationManager.removeUpdates((LocationListener) this);
  }
public void onLocationChanged(Location location) {
    double lat = (double) (location.getLatitude());
    double lng = (double) (location.getLongitude());
    Toast.makeText(getApplicationContext(), lat+"----"+lng,Toast.LENGTH_LONG).show();
    Log.i("Latitude------------", "Lattitude:" +lat);
    Log.i("Longitude-------------", "Longitude:" +lng);
  }

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}
    }

Must add required permission

Answer:

here is what i did…
1)mainactiviy.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button gpsButton = (Button) findViewById(R.id.getloc);

gpsButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
    LoadCoords();
}});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public void LoadCoords(){
EditText locn = (EditText)findViewById(R.id.text1);
EditText locn1 = (EditText)findViewById(R.id.text2);
GPSTracker gps = new GPSTracker(this);
if(gps.canGetLocation){
Double latPoint=gps.getLatitude(); 
Double lngPoint =gps.getLongitude();   

locn.setText(latPoint.toString());
locn1.setText(lngPoint.toString());
}
}
}

another file
2)GPSTracker.java

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
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;

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;

public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
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
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        }
    }

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

return location;
}
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();
}

// return longitude
return longitude;
}
@Override
public void onLocationChanged(Location location) {
}

@Override
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;
}

if it works please reply…

Answer:

    ActivityCompat.requestPermissions(MapsActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        /*
        tvLatitud.setText("No se tienen permisos");
        ...
         */

        return;
    }else
    {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        latitude = location.getLatitude();
        longitude =  location.getLongitude();
    }