-5

Hello Stack Overflowers,

I want to get the lattitude and longitude in my application.

I am using the below snippet for doing my job. But I just get the alert dialog box and when I tick mark the "Use GPS Satellites" option. I don't get anything as a output as if nothing is happening. Only GPS is being turned ON.

Could you guyz please help me by correcting the below snippet.

Sorry for the inconvenience caused to you guyz :(

And thanks for answering my previous questions. :D

Cheers!

This is a java file where I am writing all the functions related to getting Locations etc etc

GPSTracker.java

package com.iot.mymumbaimetro;

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 GPSTracker 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 = 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;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.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;
}

}

Below is the activity .java file where I am getting the current location :

TrackMyRoute.java

package com.iot.mymumbaimetro;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class TrackMyRoute extends Activity{

protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude; 
protected boolean gps_enabled,network_enabled;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.track_my_route);

    /*Set the background of the action bar to a drawable*/
    Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.red_bg);
    BitmapDrawable actionBarBackground = new BitmapDrawable(getResources(), bMap);
    getActionBar().setBackgroundDrawable(actionBarBackground);

    GPSTracker gps=new GPSTracker(TrackMyRoute.this);

 //check if GPS enabled     
    if(gps.canGetLocation()){

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        // \n is for new line
        Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
    }else{
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
    }



}

}
  • 3
    what you have tried so far? – Shayan Pourvatan Aug 18 '14 at 04:33
  • How about starting from [here](http://developer.android.com/guide/topics/location/strategies.html) or [here](http://www.vogella.com/tutorials/AndroidLocationAPI/article.html)? – Andrew T. Aug 18 '14 at 04:36
  • Hello guys please write the reason for the down vote. As this guy is new to android as well as new to stackoverflow community also. So rather down vote please try to correct him/her. – Biraj Zalavadia Aug 18 '14 at 04:41
  • 1
    The reason is lack of research, as a simple google search finds dozens of examples. But I won't add another, -4 is enough pain for this kind of mistake. – Gabe Sechan Aug 18 '14 at 04:43
  • I have tried snippets from the new boston, android hive, vogella, some other stack overflow question but to no avail :( – Venkatesh Suvarna Aug 18 '14 at 05:16
  • @GabeSechan With due respect I want to say that even -100 is not pain to me. I am only gaining knowledge not losing any. I have tried several code snippets and it hasn't worked out successfully. I know that you all know much more than me in Android ( I'm just a newbie) but it would be more grateful to you if you all could solve my problem. – Venkatesh Suvarna Aug 18 '14 at 05:42
  • 1
    @VenkateshSuvarna Oh god, I just saw you were using GPSTracker. Don't, its badly broken. Here's a blog post I wrote on why its broken, complete with alternative solution: http://gabesechansoftware.com/location-tracking/ – Gabe Sechan Aug 18 '14 at 05:49
  • So I need to add the two java files in my project? What code do I need to change in my activity(TrackMyRoute.java)? – Venkatesh Suvarna Aug 18 '14 at 06:05

1 Answers1

0

Do this way.It will show dialog if GPS is disabled and ask user to enable it. Press "YES" will take user to setting screen to enable GPS.

public void checkGPSEnabled(){
        final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

        if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
            buildAlertMessageNoGps();
        }
    }


    private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your GPS is disabled, please enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog,final int id) {
                        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

Complete guide with example to get current Location HERE

Biraj Zalavadia
  • 28,348
  • 10
  • 61
  • 77