2

I have been through lot of questions in stack overflow **but not able to solve my problem its not any spam question **

Hi everyone i am having a problem related to latitude and longitude values

iam able to fetch values in all api till Android 5.0 but from 5.1 i am facing problem i am not able to fetch values

This is what the code i am using

i have only added code which i am using to fetch permission

   if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

    } else {
        Toast.makeText(mContext, "You need have granted permission", Toast.LENGTH_SHORT).show();
        gps = new GPSTracker(mContext, MainActivity.this);

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

            getlatitude = gps.getLatitude();
            getlongitude = gps.getLongitude();

            // \n is for new line
            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + getlatitude + "\nLong: " + getlongitude, 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();
        }
    }

And then

  @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                gps = new GPSTracker(mContext, MainActivity.this);

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

                    getlatitude = gps.getLatitude();
                    getlongitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + getlatitude + "\nLong: " + getlongitude, 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();
                }

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.

                Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}

but still i am getting

Toast as Lat 0 Long 0

Info regarding gradle

i am targeting sdk 23 version

After searching few questions i came to know that we need permission to get these values can any one clearly help me in this regard

Manifest File

i have added

 <uses-permission android:name="android.permission.INTERNET" /> 
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION/>

and also Network provider permission

**

Now i have added the new code according to changes in below

**

    public class MainActivity extends Activity {



    Context context;

    double latitude_user,longitude_user;

    public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

    String[] permissions= new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};

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


        if (checkPermissions()) {

            GPSTracker gps;

            gps = new GPSTracker(context);

            latitude_user= gps.getLatitude();
            longitude_user  = gps.getLongitude();

            Toast.makeText(MainActivity.this, "Permission has been granted"+latitude_user+"  "+longitude_user, Toast.LENGTH_SHORT).show();

        }else{

            Toast.makeText(MainActivity.this, "Not granted", Toast.LENGTH_SHORT).show();

        }


    }


    private  boolean checkPermissions() {
        int result;
        List<String> listPermissionsNeeded = new ArrayList<>();
        for (String p:permissions) {
            result = ContextCompat.checkSelfPermission(getApplicationContext(),p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            }
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }
}

And GPSTracker.class

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;
            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(){

}

/**
 * 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) {
    this.location = location;
    getLatitude();
    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;
}

}
Farmer
  • 4,093
  • 3
  • 23
  • 47
Rakesh Ram
  • 19
  • 1
  • 2
  • 9

1 Answers1

0

First you need to check the os version of device then you get permission, means if device os version is 6.0 or above then getting permission dynamically is require but below then it's not require.Please You also take care about that GPS location is ON/OFF, so i suggest you that after getting permission you can also check dynamically that GPS location is ON/OFF.Please Use this one it's working in my app, i hope you also get your answer

public class GettingPermission extends AppCompatActivity {

Activity activity;

public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

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

    activity = GettingPermission.this;

    if (Build.VERSION.SDK_INT >=23)
    {
        getPermission();
    }
    else
    {
        startApp();
    }
}

private void startApp()
{
    Intent i = new Intent(activity, GetLatLog.class)
    activity.startActivity(i)
}



private void getPermission()
{
    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION)
            + ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)         
            != PackageManager.PERMISSION_GRANTED) {

        Log.i("Permission is require first time", "...OK...getPermission() method!..if");
        ActivityCompat.requestPermissions(activity,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_ID_MULTIPLE_PERMISSIONS);

    }
    else
    {
        Log.i("Permission is already granted ", "...Ok...getPermission() method!..else");
        startApp();
    }
}


@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSIONS) {
        if ((grantResults.length > 0) && (grantResults[0]+grantResults[1])
                == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.

            Log.i("onRequestPermissionsResult()...","Permission granted");
            startApp();

        } else {
            // User refused to grant permission.
            Toast.makeText(StartActivity.this, "All Permission is required to use the Screen Recorder", Toast.LENGTH_LONG).show();
            getPermission();

        }
    }
}

}

GetLatLog.java file is

public class GetLatLog extends AppCompatActivity{

    Activity activity;

    private int ENABLE_LOCATION = 100;

    double latitude = 0.0, longitude = 0.0;

    private GPSTracker gps;
    ProgressDialog pd;

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

        try
        {
            activity = GetLatLog.this;

            locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

            if (isLocationEnabled())
            {
                getLocation();
            }
            else
            {
                showSettingsAlert();
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    protected LocationManager locationManager;
    private boolean isLocationEnabled()
    {
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }

    private void getLocation()
    {
        try
        {
            if (isLocationEnabled())
            {
                gps = new GPSTracker(activity);

                // check if GPS enabled
                if(gps.canGetLocation())
                {
                    latitude = gps.getLatitude();
                    longitude = gps.getLongitude();

                    Log.i("Location", ""+latitude + " : " + longitude);

                    if(latitude == 0.0 || longitude == 0.0)
                    {
                        retryGettingLocationDialog();
                    }
                    else
                    {
                        //startYour code here, You come here after getting lat and log.
                    }
                }
                else
                {
                    Toast.makeText(activity , "Location Not Enabled", Toast.LENGTH_LONG).show();
                }
            }
            else
            {
                Toast.makeText(activity , "GPS disabled. Cannot get location. Please enable it and try again!", Toast.LENGTH_LONG).show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void showSettingsAlert()
    {

        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        activity.startActivityForResult(intent, ENABLE_LOCATION);

    }

    public void retryGettingLocationDialog()
    {
        retryGettingLocation();
    }

    private void retryGettingLocation()
    {
        try
        {
            new AsyncTask<Void, Void , Void>()
            {
                @Override
                protected void onPreExecute()
                {
                    try {
                        pd = new ProgressDialog(activity);
                        pd.setCancelable(false);
                        pd.setMessage("Please while we retry getting your location...");
                        pd.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    super.onPreExecute();
                }

                @Override
                protected Void doInBackground(Void... params)
                {
                    try
                    {
                        Thread.sleep(1500);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid)
                {
                    super.onPostExecute(aVoid);

                    if(pd != null)
                    {
                        pd.cancel();
                        pd.dismiss();
                        pd = null;
                    }

                    getLocation();
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        try {
            //if (resultCode == Activity.RESULT_OK)
            {
                if(requestCode == ENABLE_LOCATION)
                {
                    if (isLocationEnabled())
                    {
                        getLocation();
                    }
                    else
                    {
                        showSettingsAlert();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Farmer
  • 4,093
  • 3
  • 23
  • 47
  • Which device you can run you app – Farmer Oct 01 '16 at 06:54
  • i want to run in all api starting from api 15 to api 23 – Rakesh Ram Oct 01 '16 at 06:59
  • if API level 23 then we need to get dynamic permission else not require as i explained in my answer, if your API level is less then 23 then also it works fine. please check my up dated answer. it will work in all API level – Farmer Oct 01 '16 at 07:40
  • hi i will check updated code and your old code worked for me i got longitude and latitude values in marshmallow and all api's but not in (lenevo k4 note) -> lollipop(5.1) but i also got in api 5.0 will let u know regarding new code in a day thanks .. – Rakesh Ram Oct 01 '16 at 13:24
  • and i also use genymotion all api's till kitkat working but lollipop and marshmallow emulators are not at all starting unable to start with virtual device error while other devices are working fine – Rakesh Ram Oct 01 '16 at 13:29