Strange issue in finding GPS - android

Hai all i want to find current GPS location, i have used the following code.
public class GPSManager
{
private static final int gpsMinTime = 500;
private static final int gpsMinDistance = 0;
private LocationManager locationManager = null;
private LocationListener locationListener = null;
private GPSCallback gpsCallback = null;
public GPSManager()
{
locationListener = new LocationListener()
{
public void onProviderDisabled(final String provider)
{
}
public void onProviderEnabled(final String provider)
{
}
public void onStatusChanged(final String provider, final int status, final Bundle extras)
{
}
public void onLocationChanged(final Location location)
{
location.getLatitude();
location.getLongitude();
if (location != null && gpsCallback != null)
{
Log.e("if location "+location,"if gpscallback"+gpsCallback);
gpsCallback.onGPSUpdate(location);
location.getLatitude();
location.getLongitude();
}
else{
Log.e("else location "+location,"else gpscallback"+gpsCallback);
}
}
};
}
public void startListening(final Activity activity)
{
if (locationManager == null)
{
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
}
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String bestProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider != null && bestProvider.length() > 0)
{
locationManager.requestLocationUpdates(bestProvider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, locationListener);
}
else
{
final List<String> providers = locationManager.getProviders(true);
for (final String provider : providers)
{
locationManager.requestLocationUpdates(provider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, locationListener);
}
}
}
public void stopListening()
{
try
{
if (locationManager != null && locationListener != null)
{
locationManager.removeUpdates(locationListener);
}
locationManager = null;
}
catch (final Exception ex)
{
}
}
public void setGPSCallback(final GPSCallback gpsCallback)
{
this.gpsCallback = gpsCallback;
}
public GPSCallback getGPSCallback()
{
return gpsCallback;
}
But strange issue is it is working only when GPS in mobile is off mode. If GPS in device is in on Mode it is not working.
Can anybody please tell me what is the issue with my code?
Please help me... thanks in advance.

The problem should be the power requirement. You're requesting for everything that matchs the gps provider ( Location fine .... ) but gps is power consuming so try to remove that line or setting the criteria to POWER_HIGH

Related

Android GPS showing different location and counting wrong distance

i'm making app where i using GPS and counting traveled distance, i'm downloading current loaction and counting distance between two location. When i'm trying to get current location it is showing me different location (i don't move my phone) and when i'm trying to count distance i'm geting wrong result :/ here source code
GPSTracker:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
public static double distance=0;
Location location1,location2;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Activity activity;
Location location;
double latitude;
double longitude;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 50;
private static final long MIN_TIME_BW_UPDATES = 1000 * 10;
protected LocationManager locationManager;
public GPSTracker(Context context, Activity activity) {
this.mContext = context;
this.activity = activity;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
int requestPermissionsCode = 50;
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestPermissionsCode);
} else {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
if(isGPSEnabled) {
if(location == null) {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
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;
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
if(location1 == null){
location1 = location;
} else {
location2 = location1;
location1 = location;
distance += location1.distanceTo(location2) / 1000f;
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
DistanceActivity:
public class DistanceActivity extends Activity{
Button startB, stopB;
TextView textView;
GPSTracker gps;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distance);
startB = findViewById(R.id.start_B);
stopB = findViewById(R.id.stop_B);
textView = findViewById(R.id.distance_TV);
mContext = this;
startB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gps = new GPSTracker(mContext,DistanceActivity.this);
if(gps.canGetLocation()){
textView.setText("Distance: "+String.format("%.2f Km",gps.distance ));
} else {
textView.setText("Cannot count distance.");
}
}
});
}
}

getLastKnownLocation sometimes returns null

Let me start by acknowledging that there are many results when you search for this particular question. Yet, nothing I've tried, according to those answers, works. Sometimes I get the location, sometimes I don't. If I play with the Location enabling/disabling I always get null when calling getLastKnownLocation. If I sometimes manually revoke the Location permission and enable it again, it works. I've tried changing the LocationManager to location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); but it doesn't work.
Basically, I am doing the following:
public class GPSTracker implements LocationListener {
public static final int LOCATION_SETTINGS_REQUEST_CODE = 109;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;
private static boolean isGpsStatusChanged = false;
private static AlertDialog.Builder alertDialog;
private LocationManager locationManager;
private boolean canGetLocation = false;
private Location location;
private double latitude;
private double longitude;
private NewLocationListener newLocationListener;
public interface NewLocationListener {
void onLocationChanges(Location location);
}
public GPSTracker() {
}
#SuppressWarnings("all")
public Location getLocation() {
try {
locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean 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("GPSTracker", "Network");
if (locationManager != null) {
Log.d("GPSTracker", "Network - location manager != null");
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("GPSTracker", "Network - last known location != null");
latitude = location.getLatitude();
longitude = location.getLongitude();
newLocationListener.onLocationChanges(location);
}
}
}
// 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("GPSTracker", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("LastKnownLocation", "Location: " + locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
newLocationListener.onLocationChanges(location);
}
}
}
}
}
} catch (Exception e) {
Log.e(Constants.TAG, e.getMessage(), e);
}
return location;
}
public static boolean isGpsEnabled() {
LocationManager locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context
.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
#SuppressWarnings("all")
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void setNewLocationListener(NewLocationListener newLocationListener) {
this.newLocationListener = newLocationListener;
}
public void removeLocationListener() {
this.newLocationListener = null;
}
#SuppressWarnings("InlinedApi")
public void showSettingsAlert(final Context context) {
if (alertDialog != null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alertDialog = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
alertDialog = new AlertDialog.Builder(context);
}
alertDialog.setTitle(R.string.gps_window_title);
alertDialog.setMessage(R.string.gps_window_message);
alertDialog.setPositiveButton(R.string.gps_window_button_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
((Activity) context).startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE);
}
});
alertDialog.setNegativeButton(R.string.gps_window_button_negative, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show().setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
alertDialog = null;
}
});
}
#Override
public void onLocationChanged(Location location) {
if (newLocationListener != null) {
newLocationListener.onLocationChanges(location);
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public static boolean isGpsStatusChanged() {
return isGpsStatusChanged;
}
public static void setIsGpsStatusChanged(boolean isGpsStatusChanged) {
GPSTracker.isGpsStatusChanged = isGpsStatusChanged;
}
}
And then in my fragment:
private void statGPSLocationTracking() {
Log.d(Constants.TAG, "start gps update");
// check if GPS enabled
gpsTracker = new GPSTracker();
gpsTracker.setNewLocationListener(newLocationListener);
gpsTracker.getLocation();
if (!gpsTracker.canGetLocation()) {
Log.d(Constants.TAG, "GPS not enabled, show enable dialog");
// stop the gps tracker(removes the location update listeners)
gpsTracker.stopUsingGPS();
// ask user to enable location
gpsTracker.showSettingsAlert(getActivity());
}
}
private GPSTracker.NewLocationListener newLocationListener = new GPSTracker.NewLocationListener() {
#Override
public void onLocationChanges(Location loc) {
if (getActivity() == null) {
return;
}
// GPS location determined, load the web page and pass the coordinates in the header location section
Log.d(Constants.TAG, "Location listener onLocationChanges: " + loc);
infoManager.setCurrentLocation(loc);
checkRadioInfoNeeded();
// stop the gps tracker(removes the location update listeners)
gpsTracker.stopUsingGPS();
}
};
Without this location permission android.Manifest.permission.ACCESS_FINE_LOCATION the getLastKnownLocation() will always return null.
getLastKnownLocation() does not return location immediately, it takes some time.
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;
this to
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 5 * 1000;
Also remove your code which gets location from network. Go to Google maps and see if maps is able to detect your current location. If your map is able to get location then your code too should get location place breakpoints and see where the real issue is.

location with internet service provider(network provider)

Hello I have class that looks up for your location, first with network provider, then waits for GPS provider info. I don't know why, but I never get information from network provider, GPS works well, when signal is acquired.
public class GpsListener {
public static GpsListener refrence = null ;
public LocationManager locationManager = null;
public LocationListener locationListener = null;
public Location location = null;
public static GpsListener getInstance(){
if(refrence == null){
refrence = new GpsListener();
}
return refrence;
}
public void startGpsCallBack(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Map.MyPositionlatitude = location.getLatitude();
Map.MyPositionlongitude = location.getLongitude();
}
}
public class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Map.MyPositionlatitude = location.getLatitude();
Map.MyPositionlongitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void stopGpsCallBack(){
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startGpsCallbackAgain(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Map.MyPositionlatitude = location.getLatitude();
Map.MyPositionlongitude = location.getLongitude();
}
}
}
use google play serivces it is more simple

Why current location of android phone don't change when i change location?

I get location of android phone as:
android.location.Location locationA;
LocationManager locationManager;
Criteria cri = new Criteria();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String tower = locationManager.getBestProvider(cri, false);
locationA = locationManager.getLastKnownLocation(tower);
if (locationA != null) {
// lat = (double) (locationA.getLatitude() * 1E6);
// longi = (double) (locationA.getLongitude() * 1E6);
double lat = locationA.getLatitude();
double longi = locationA.getLongitude();
TextView txt = (TextView) findViewById(R.id.textView1);
String td = String.valueOf(lat) + "," + String.valueOf(longi);
txt.setText(td);
}
Why current location of android phone don't change when i change location and get again current location?
check the time of your location using locationA.getTime(). if it was not up to date wait for a new location and then stop.
private static Location currentLocation;
private static Location prevLocation;
public void yourMethod()
{
locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST,
MIN_DISTANCE, locationListener);
}
private static LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
gotLocation(location);
}
};
private static void gotLocation(Location location) {
prevLocation = currentLocation == null ?
null : new Location(currentLocation);
currentLocation = location;
if (isLocationNew()) {
// do something
locationManager.removeUpdates(locationListener);
}
}
private static boolean isLocationNew() {
if (currentLocation == null) {
return false;
} else if (prevLocation == null) {
return false;
} else if (currentLocation.getTime() == prevLocation.getTime()) {
return false;
} else {
return true;
}
}

How to GPS Start and Stop depending upon my application?

I want to implement whenever I launch my android
application,that time I want to start gps,
Whenever I close
application, I want to stop gps in device. How to implement
this concept in my application ?
The most important thing is to remove the LocationListener in all onPause methods of your Activities. You then can restart the listening in your onResume methods.
If you don't remove the listener in the onPause method the GPS will be active even if your app is the paused in the background. See the activity lifecycle for more information.
John, you need to use the LocationManager class. Here is a tutorial on how to get the users location.
First add bellow Class and interface to your application.
public class GPSManager
{
private static final int gpsMinTime = 500;
private static final int gpsMinDistance = 0;
private LocationManager locationManager = null;
private LocationListener locationListener = null;
private GPSCallback gpsCallback = null;
public GPSManager()
{
locationListener = new LocationListener()
{
public void onProviderDisabled(final String provider)
{
}
public void onProviderEnabled(final String provider)
{
}
public void onStatusChanged(final String provider, final int status, final Bundle extras)
{
}
public void onLocationChanged(final Location location)
{
if (location != null && gpsCallback != null)
{
Log.e("if location "+location,"if gpscallback"+gpsCallback);
gpsCallback.onGPSUpdate(location);
}
else{
Log.e("else location "+location,"else gpscallback"+gpsCallback);
}
}
};
}
public void startListening(final Activity activity)
{
if (locationManager == null)
{
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
}
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String bestProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider != null && bestProvider.length() > 0)
{
locationManager.requestLocationUpdates(bestProvider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, locationListener);
}
else
{
final List<String> providers = locationManager.getProviders(true);
for (final String provider : providers)
{
locationManager.requestLocationUpdates(provider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, locationListener);
}
}
}
public void stopListening()
{
try
{
if (locationManager != null && locationListener != null)
{
locationManager.removeUpdates(locationListener);
}
locationManager = null;
}
catch (final Exception ex)
{
}
}
public void setGPSCallback(final GPSCallback gpsCallback)
{
this.gpsCallback = gpsCallback;
}
public GPSCallback getGPSCallback()
{
return gpsCallback;
}
}
Interface:
public interface GPSCallback
{
public abstract void onGPSUpdate(Location location);
}
then implement this interface in your activity and also add below code in your activity
gpsmanager=new GPSManager();
gpsmanager.startListening(YourActicvityname.this);
gpsmanager.setGPSCallback(this);
To stop GPS call gpsmanager.stopListening() at where you want to close the application

Categories

Resources