0

Have been trying to get my application location to work with the new marshmallow format but have been getting null and not been able to figure it out as it has been giving me a lot of headaches for days now. This is my present location service class

public class GPSService extends Service implements LocationListener {

// saving the context for later use
private final Context mContext;

// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;

// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;

// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 300;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;

// Declaring a Location Manager
protected LocationManager mLocationManager;

public GPSService(Context context) {
    this.mContext = context;
    mLocationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);

}


public Location getLocation() {
    try {

        // Getting GPS status
        isGPSEnabled = mLocationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // If GPS enabled, get latitude/longitude using GPS Services
        if (isGPSEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                    // location is available
                    return mLocation;
                }
            }
        }

        // If we are reaching this part, it means GPS was not able to fetch
        // any location
        // Getting network status
        isNetworkEnabled = mLocationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled) {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
            if (mLocationManager != null) {
                mLocation = mLocationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (mLocation != null) {
                    mLatitude = mLocation.getLatitude();
                    mLongitude = mLocation.getLongitude();
                    isLocationAvailable = true; // setting a flag that
                    // location is available
                    return mLocation;
                }
            }
        }
        // If reaching here means, we were not able to get location neither
        // from GPS not Network,
        if (!isGPSEnabled) {
            // so asking user to open GPS
            askUserToOpenGPS();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    // if reaching here means, location was not available, so setting the
    // flag as false
    isLocationAvailable = false;
    return null;
}

/**
 * Gives you complete address of the location
 *
 * @return complete address in String
 */
public String getLocationAddress() {

    if (isLocationAvailable) {

        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
        // Get the current location from the input parameter list
        // Create a list to contain the result address
        List<Address> addresses = null;
        try {
            /*
             * Return 1 address.
             */
            addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
        } catch (IOException e1) {
            e1.printStackTrace();
            return ("IO Exception trying to get address:" + e1);
        } catch (IllegalArgumentException e2) {
            // Error message to post in the log
            String errorString = "Illegal arguments "
                    + Double.toString(mLatitude) + " , "
                    + Double.toString(mLongitude)
                    + " passed to address service";
            e2.printStackTrace();
            return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {
            // Get the first address
            Address address = addresses.get(0);
            /*
             * Format the first line of address (if available), city, and
             * country name.
             */
            String addressText = String.format(
                    "%s, %s, %s,%s",
                    // If there's a street address, add it
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "",
                    // Locality is usually a city
                    address.getLocality(),
                    address.getAdminArea(),
                    // The country of the address
                    address.getCountryName());
            // Return the text
            return addressText;
        } else {
            return getString(R.string.no_address_gpsservice);
        }
    } else {
        return getString(R.string.loc_unavaliable);
    }

}



/**
 * get latitude
 *
 * @return latitude in double
 */
public double getLatitude() {
    if (mLocation != null) {
        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}

/**
 * get longitude
 *
 * @return longitude in double
 */
public double getLongitude() {
    if (mLocation != null) {
        mLongitude = mLocation.getLongitude();
    }
    return mLongitude;
}

/**
 * close GPS to save battery
 */
public void closeGPS() {

    if (mLocationManager != null) {
        mLocationManager.removeUpdates(GPSService.this);
    }
}

/**
 * show settings to open GPS
 */
public void askUserToOpenGPS() {
    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    mAlertDialog.setTitle(R.string.gpsservice_dialog_title)
            .setMessage(R.string.gpsservice_dialog_message)
            .setPositiveButton(R.string.gpsservice_dialog_positive, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            })
            .setNegativeButton(R.string.gpsservice_dialog_negative,new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }).show();
}

/**
 * Updating the location when location changes
 */
@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
}

@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;
}
  • is the any error in your logcat and have you requested permissions in your manifest and in code too. You know marshmallow has a new way of handling permissions – Mueyiwa Moses Ikomi Aug 29 '16 at 15:48
  • its the new way i don't understand, have read a lot of replies on it but i don't get it, applied it the same way they did but i get null @MueyiwaMosesIkomi – Clara Raymond Aug 29 '16 at 15:51
  • your question has been dubbed as duplicate so i won't be able to post an answer but are you sure your gps is picking locations. Check with another gps app. If u get readings, then try your app. Gps can b difficulty to acquire in some areas. – Mueyiwa Moses Ikomi Aug 29 '16 at 15:53
  • the gps presently works for other versions i just need to adjust it for marshmallow @MueyiwaMosesIkomi – Clara Raymond Aug 29 '16 at 15:55
  • let me break down how i get my permissions in mashmallow... – Mueyiwa Moses Ikomi Aug 29 '16 at 15:58
  • private static final int PERMS_REQUEST_CODE = 123; – Mueyiwa Moses Ikomi Aug 29 '16 at 15:58
  • //Handle Permissions private boolean hasPermissions(){ int res = 0; String [] permissions = new String[]{android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.RECEIVE_SMS, android.Manifest.permission.READ_SMS}; for( String perms : permissions){ res = checkCallingOrSelfPermission(perms); if(!(res == PackageManager.PERMISSION_GRANTED)){ return false; } } return true; } – Mueyiwa Moses Ikomi Aug 29 '16 at 15:58
  • private void requestPerms(){ String [] permissions = new String[]{android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.RECEIVE_SMS, android.Manifest.permission.READ_SMS}; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ requestPermissions(permissions, PERMS_REQUEST_CODE); } } – Mueyiwa Moses Ikomi Aug 29 '16 at 15:58
  • you need to ask for permission at runtime which is explained in the other question that we marked duplicate and in the android documentation https://developer.android.com/training/permissions/requesting.html – tyczj Aug 29 '16 at 16:00
  • theres an onRequestPermissions ...but too long for comments. Do you get the permissions to pop up when you run the your app at runtime? – Mueyiwa Moses Ikomi Aug 29 '16 at 16:00
  • the process of requesting for permission is when it breaks down – Clara Raymond Aug 29 '16 at 16:03
  • and you sure you also have that permission in ur manifest. Where can i post you the full code? – Mueyiwa Moses Ikomi Aug 29 '16 at 16:08
  • can u put it in a notepad and send via mail thanks a lot. i have permission in manifest. – Clara Raymond Aug 29 '16 at 16:14
  • hamanambu@gmail.com – Clara Raymond Aug 29 '16 at 16:19
  • sent, hope it helps... – Mueyiwa Moses Ikomi Aug 29 '16 at 16:27

0 Answers0