0

i need to get myLocation using GPS, how to get it? I try next code, but it works not ever. When i restart my phone and run application it does not works.

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
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.provider.Settings;
import android.util.Log;

public class GPSTraker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
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 = 1; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 3000; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTraker(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;
            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;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTraker.this);
    }
}

/**
 * Function to get latitude
 * */
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;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog
            .setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    // Showing Alert Message
    alertDialog.show();
}

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

}
 }

and using it:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_near_new, null);
    elvMain = (ExpandableListView) v.findViewById(R.id.elvMain);
    GPSTraker gps = new GPSTraker(getActivity());

    if (gps.canGetLocation()) {
        myLat = gps.getLatitude();
        myLong = gps.getLongitude();
        Log.d("myDebug", "new get Location +" + myLat);
        // \n is for new line

    } else {
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        Log.d("myDebug", "Can not get location");
        gps.showSettingsAlert();
    }


    return v;
}

What it is wrong? Maybe someone have some ideas how to solve this? After i reboot my phone this program can not get my location too.

1 Answer 1

1

Do you want continuous location updates or just a single location?

By "GPS, without network" I assume that you want to get a location even when the network is not available, not that the network location should never be used.

Some basics on LocationManager:

On startup, you need to request an instance of LocationManager and then call RequestLocationUpdates(), passing as an argument the class that will receive location updates. When a new location is available, LocationManager will call onLocationChanged(), passing the current location as an argument.

Looking at your code, you have it all there, but in the wrong places:

  • Most of the code in your getLocation() method should go into onCreate().
  • The call to requestLocationUpdates() should go in your service's onStartCommand() method. You should unregister by calling removeUpdates() in your stopSelf() method so that the GPS will be released when your service is stopped. (For an Activity, do this in onResume() and onPause(), respectively. Otherwise it will keep the GPS awake and drain the battery even after the service stops/user navigates away from the activity, until the system kills the app.)
  • The code for handling a location update, which you have placed in onCreateView(), should go into onLocationChanged().

I see you are also calling LocationManager.getLastKnownLocation(). This will get the last location that LocationManager has previously obtained, but it will not start the GPS. If no other app has requested a location update before (using requestLocationUpdates()), it has no location to report, and if the device moved since the last position was obtained, you will get an out-of-date position.

If you need a single location update in a reliable fashion and with up-to-date information, follow the instructions above and place the call to removeUpdates() in your onLocationChanged() method. That will release the GPS after the first location update. Note that you may have to wait some time for the location update, as the GPS may take some time to start up.

3
  • i will try it now and sent you my result, i want to updates my location every 30 sec. Sep 20, 2013 at 11:20
  • "Most of the code in your getLocation() method should go into onCreate()." onCreate method of class that calls gpsTracker? Sep 20, 2013 at 11:21
  • The onCreate() method of the Service which you have already created. I just saw that the class is a Service, not an Activity, and updated my answer accordingly.
    – user149408
    Sep 20, 2013 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.