0
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private final FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;


private double currentLattitude;
private double currentLongitude;

Button button;
TextView textView;


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


    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();


    button = (Button) findViewById(R.id.btn_start);
    textView = (TextView) findViewById(R.id.txt_route);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            textView.setText(String.valueOf(currentLattitude + currentLongitude));



        }
    });
}

@Override
protected void onResume() {
    super.onResume();

    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();

    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnected(Bundle arg0) {
    final LocationRequest locationRequest = LocationRequest.create();
    locationRequest
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient,
            locationRequest, this);


    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (location == null) {

//            
  LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

        fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient,
                locationRequest, this);

       // currentLattitude = location.getLatitude();
       // currentLongitude = location.getLongitude();
        Log.e("Lat" , ""  +currentLattitude);
        Log.e("Long" , ""  +currentLongitude);



    } else {

        currentLattitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        Log.e("Lat" , ""  +currentLattitude);
        Log.e("Long" , ""  +currentLongitude);

    }
}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onLocationChanged(Location location) {
    // the location is no more than 10 min old, and with reasonable
    // accurarcy (50m), done
    if (System.currentTimeMillis() < location.getTime() + 10 * 60 * 1000
            && location.getAccuracy() < 50) {
        mGoogleApiClient.disconnect();
        mGoogleApiClient = null;
    }
}
}

In my app i get the lat long of user without enabling the GPSLocation of Mobile . I tried with this code a lot but this code always throws the LAT LONG 0.0 . Please help me with this issue . Tell me what will be the issue with this code.?

  • try to match your code with this one http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/ – 9spl Apr 06 '17 at 06:57

3 Answers3

0

So basically , Manifest.permission.ACCESS_FINE_LOCATION - this will work with GPS Manifest.permission.ACCESS_COARSE_LOCATION - this will work with Network

So change your && with || will work for you , currently you are asking that both should be Permitted.

if (ActivityCompat.checkSelfPermission(this, `Manifest.permission.ACCESS_FINE_LOCATION`) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
9spl
  • 357
  • 1
  • 11
0

You should get coordinates in the 'onLocationChanged' callback, by getting latitude and longitude from the Location object passed in the function. Also check if your manifest has this:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
JamesRGNT
  • 586
  • 1
  • 6
  • 17
  • Ok but did you try to get latitude and longitude in the callback? If it still doesn't work, look here http://stackoverflow.com/questions/6694391/android-get-current-location-of-user-without-using-gps-or-internet – JamesRGNT Apr 06 '17 at 07:29
0

Add this code in "OnCreate":


// CHECK LOCATION SERVICES IS ON
        LocationManagerControl locationManagerControl = new LocationManagerControl(this);
        try {
            if (locationManagerControl.isLocationServiceAvailable()) {
                try {
                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                locationListener = new LocationListener() {
                    // @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                    }

                    // @Override
                    public void onLocationChanged(Location location) {
                        user_lat = location.getLatitude();
                        user_lng = location.getLongitude();

                    }
                };


            } else {
                locationManagerControl.createLocationServiceError(MainActivity.this);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

And you want to call it wherever you want:

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

And don't forget to add:

LocationManager locationManager;
LocationListener locationListener;

And add the following permissions to your application in your AndroidManifest.xml file

  • INTERNET
  • ACCESS_FINE_LOCATION
  • ACCESS_COARSE_LOCATION

I hope this helps..

Hilalkah
  • 945
  • 15
  • 37