0

I am new to a service. I want to turn on my GPS sensor and get the lat and long coordinate of GPS. I am using Android M, I provided the permission for my app. However, I cannot enable and get coordinate. Could you help me?

code :

//Enable gps
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")) {
    new Handler(getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    });
}
Akash Patel
  • 2,706
  • 1
  • 20
  • 28
John
  • 2,550
  • 7
  • 28
  • 62

3 Answers3

1

first you need to set up the permission in manifest file

 <manifest ... >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />

class which will be used to find out location

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

}

for fetching location

  GPSTracker gps = new GPSTracker(this);


if(gps.canGetLocation())
{
  gps.getLatitude(); // returns latitude
  gps.getLongitude(); //
}

Refrences taken from:http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

Navneet Kumar
  • 248
  • 1
  • 11
  • Thanks for your solution. However, I am running the app in the Android M. It required the `ActivityCompat.checkSelfPermission` before calling `locationManager.requestLocationUpdates`. I tried it but I was error `java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference` – John Mar 05 '17 at 06:17
  • can you attach the screen shots of particular screen , so that i can look into it , may be then only i will be able to tell – Navneet Kumar Mar 05 '17 at 06:56
  • I found a good solution here http://stackoverflow.com/questions/36915290/getting-latitude-and-longitude-0-0-in-android-m – John Mar 05 '17 at 07:04
0

You can not switch on or switch off GPS programatically in android. Could you clearify your question more, whether you are getting trouble in switching GPS on and off or in getting lat long` if the problem is switching it on and off then you can guide the user to setting screen and ask them to switch on user when ever you need , here is code

`final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
 new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
 startActivity(intent);
}`

`

Navneet Kumar
  • 248
  • 1
  • 11
  • Yes. First. My GPS is turn off now. I want to use programmatically to turn on it. Then. I want to get the coordinate value from the sensor. Thanks – John Mar 04 '17 at 11:59
  • The one which you used is an exploit , it might not work for your device – Navneet Kumar Mar 04 '17 at 12:20
  • Thanks. SO could you give me the way to get coordinate with simple way? Assume that GPS is on now – John Mar 04 '17 at 15:04
0

first you need run time permission for location in marshmallow android version

add your main activity

in oncreate() method

 if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.d("PLAYGROUND", "Permission is not granted, requesting");
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 123);

    } else {
        Log.d("PLAYGROUND", "Permission is granted");
    }

below oncreate() method

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == 123) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.d("PLAYGROUND", "Permission has been granted");

        } else {
            Log.d("PLAYGROUND", "Permission has been denied or request cancelled");
            finish();
        }
    }
}

and then as usual your stuff

Akash pasupathi
  • 304
  • 1
  • 14