I am trying to update the users location every second (every second I want a log message to appear which contains the actual position of the user), for this I have to ask the user at run time if he wants to allow the app to get access to his position only once (I have to ask because API 24 requires this). After the user has accepted the app does not ask again.
But onLocationChanged does not get called.
#Override
protected void onCreate(Bundle bundle) {
//initializing UI
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
mLocationRequest.setInterval(1000);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
return;
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == 1) {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults.length > 0) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
Log.i("LOCATION", location.toString());
}
Related
So i want to display my latitude and longitude of the position, however it shows me only when i launch the app again.
When i install the app, and launch it for the first time there is no position received.
What is the simple way to get the current location for the first time? What i am doing wrong? I run this on emulator with API 24.
Here is my code:
private final static String LOG_TAG = MainActivity.class.getName();
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
private TextView locationLatitude;
private TextView locationLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationLatitude = (TextView) findViewById(R.id.latitude_text);
locationLongitude = (TextView) findViewById(R.id.longitude_text);
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
private void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(LOG_TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(Build.VERSION.SDK_INT < 21){
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
else {
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) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else{
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
if(lastLocation != null){
locationLatitude.setText(String.valueOf(lastLocation.getLatitude()));
locationLongitude.setText(String.valueOf(lastLocation.getLongitude()));
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
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) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
}
}
#Override
public void onConnectionSuspended(int i) {
Log.d(LOG_TAG, "onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(LOG_TAG, "onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
Log.d(LOG_TAG, "onLocationChanged");
locationLatitude.setText(String.valueOf(location.getLatitude()));
locationLongitude.setText(String.valueOf(location.getLongitude()));
}
You never request location updates.
Try this:
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(LOG_TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
if(Build.VERSION.SDK_INT < 21){
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
else {
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) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else{
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
}
if(lastLocation != null){
locationLatitude.setText(String.valueOf(lastLocation.getLatitude()));
locationLongitude.setText(String.valueOf(lastLocation.getLongitude()));
}
}
Can anybody help me to solve problem:
onConnected() method why my
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
code not executing; and retrun from checkSelfPermission()
what can i do to work FusedLocationApi properly in this code
my code is below
public class JMSCLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final String TAG = "MyAwesomeApp";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
// Check Permissions Now
private static final int REQUEST_LOCATION = 2;
//private final double radiusInMeters = 1609.34;
private final double radiusInMeters = 16.34;
LatLng firstLatLong;
Location fLoc;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "GoogleApiClient connection has STARTED");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
firstLatLong = new LatLng(0, 0);
Log.i(TAG, "GoogleApiClient connection has STARTED");
}
#Override
public void onDestroy() {
// disconnect the client.
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Connect the client.
if (mGoogleApiClient != null && !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
Log.i(TAG, "GoogleApiClient mGoogleApiClient.connect();");
}
if (mGoogleApiClient.isConnected()) {
Log.i(TAG, "GoogleApiClient mGoogleApiClient.isConnected();");
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
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) {
// 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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "GoogleApiClient connection has been suspend");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "GoogleApiClient connection has failed");
}
#Override
public void onLocationChanged(Location mCurrentLocation) {
Log.i(TAG, "GoogleApiClient Location received: " + mCurrentLocation.toString());
//test outside
double mLatitude = mCurrentLocation.getLatitude();
double mLongitude = mCurrentLocation.getLongitude();
if(firstLatLong.latitude == 0.0 && firstLatLong.longitude == 0.0){
firstLatLong = new LatLng(mLatitude,mLongitude);
fLoc=new Location(mCurrentLocation);
}
float[] results = new float[1];
Location.distanceBetween(firstLatLong.latitude, firstLatLong.longitude,
mLatitude, mLongitude, results);
float distanceInMeters = fLoc.distanceTo(mCurrentLocation);
try{
if( distanceInMeters > radiusInMeters ){
Toast.makeText(getBaseContext(), "Outside, distance from center", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center", Toast.LENGTH_LONG).show();
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
USE:
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ID);
}else{
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
AND:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_ID: {
for( int i = 0; i < permissions.length; i++ ) {
if( grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Log.d("Permissions", "Permission Granted: " + permissions[i]);
} else if( grantResults[i] == PackageManager.PERMISSION_DENIED ) {
Log.d( "Permissions", "Permission Denied: " + permissions[i] );
}
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
You have to request the permissions. You are just checking whether your app has the permission.
You are ignoring the result of checkSelfPermission() in your code.
Read the comments, they are self explanatory.
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) {
// 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;
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
Read about requesting runtime permissions from :
https://developer.android.com/training/permissions/requesting.html#perm-request
http://www.truiton.com/2016/04/obtaining-runtime-permissions-android-marshmallow-6-0/
Edit 1
I think by ...but at compile time in service it's gives error for must use selfcheck permission you mean the Lint warnings.
You can suppress them by adding #SuppressWarnings("MissingPermission") on top of the method in which you are calling requestLocationUpdates().
But make sure you have are calling requestLocationUpdates() iff you have the permission for it (Mind the if..else block).
I want to get the location of the device at app startup.
I have been looking through the docs, trying to figure out what goes wrong, but I can't seem to find it. onLocationChanged is never called.
private void getLocation() {
// Connected to Google API
// Create location request with minimum interval of a minute, and normal of an hour
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setFastestInterval(1000 * 60);
mLocationRequest.setInterval(1000 * 60 * 60);
// Request permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{"ACCESS_FINE_LOCATION"}, MY_PERMISSION_LOCATION_CODE);
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_LOCATION_CODE: {
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
else {
TextView loading = (TextView)findViewById(R.id.connecting_text);
loading.setText("Please enable Location under Settings > Apps > Beet > Permissions.");
loading.setTextSize(20);
}
break;
}
}
}
public void onLocationChanged(Location location) {
System.out.println("GETLOCATION1 ________________");
mLastLocation = location;
System.out.println(location.getLatitude() + " - " + location.getLongitude() + " ________________");
}
Try getting permission like this: it works in my case
if (!checkIfAlreadyhavePermission()) {
ActivityCompat.requestPermissions(this, new String[]{"ACCESS_FINE_LOCATION"}, MY_PERMISSION_LOCATION_CODE);
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_LOCATION_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Call_location_updates();
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.gps_permission), Toast.LENGTH_LONG).show();
finish();
}
break;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Also create your LocationRequest object like this:
private final int INTERVAL = 5000;
private final int FAST_INTERVAL = 1000;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FAST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
public void Call_location_updates(){
Location location = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (location != null) {
onLocationChanged(location);
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
//do what u want with location
}
I am trying to get the current location, the code works most of the times. But location updates fail to work in a tunnel, despite the fact that mobile reception presents.
I have tried and traced through the following two methods:
Location NetLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location GPSLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Neither seems to update in the tunnel. I have cross checked with a few other apps and noticed that location service is working correctly in google map.
Whole function is linked here
So is there anyways I could get correct location updates in a tunnel?
Google has this new API called fusedLocationAPI, you could probably try using that. Here's the sample code -
public class YourActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static final int LOCATION_PERMISSION_CODE = 42;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
initGoogleApiClient();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_CODE);
} else {
getLastKnownLocation();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastKnownLocation();
} else {
startLocationActivity();
}
}
}
private void getLastKnownLocation() {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
private void initGoogleApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
}
This is just a higher-level overview of what could be done. The code could be further customized by adding location update intervals and so on. You could refer this site - https://developer.android.com/training/location/retrieve-current.html for further info.
Let's say I can get my location real time in a fragment and now I have another activity I need to get the real time location from this mapTabFragment and how can i do this. since I already have my real time location in this fragment all i wanna do is use this result in my another activity. i just need the latlng ...
public class MapTabFragment extends Fragment implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
List<ParseObject> parseObjectsList;
ArrayList<Post> postsList;
private static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 200;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_tab, container, false);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment =
(SupportMapFragment) fm.findFragmentById(R.id.mapView);
// mapFragment.getMapAsync(this);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postsList = new ArrayList<>();
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//connect here or at onStart()?
mGoogleApiClient.connect();
// buildGoogleApiClient();
if(checkGooglePlayServices()){
buildGoogleApiClient();
}
createLocationRequest();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// mGoogleApiClient.connect();
}
private boolean checkGooglePlayServices() {
int checkGooglePlayServices = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getContext());
if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
/*
* google play services is missing or update is required
* return code could be
* SUCCESS,
* SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED,
* SERVICE_DISABLED, SERVICE_INVALID.
*/
GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices,
getActivity(), REQUEST_CODE_RECOVER_PLAY_SERVICES).show();
return false;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_RECOVER_PLAY_SERVICES) {
if (resultCode == Activity.RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getContext(), "Google Play Services must be installed.",
Toast.LENGTH_SHORT).show();
//finish();
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if(mGoogleApiClient.isConnected()){
Log.d("map","Google_Api_Client: It was connected on (onConnected) function, working as it should.");
}
else{
Log.d("map failed","Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged.");
}
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
}
// mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
// mGoogleApiClient);
if (mLastLocation != null) {
Toast.makeText(getContext(), "Latitude:" + mLastLocation.getLatitude()+", Longitude:"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
}
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(20000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates(){
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Toast.makeText(getContext(), "Latitude:" + mLastLocation.getLatitude()+", Longitude:"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void stopLocationUpdates(){
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
}
// #Override
// public void onMapReady(GoogleMap googleMap) {
// mGoogleMap = googleMap;
// mGoogleMap.setMyLocationEnabled(true);
// mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
//
// LocationManager locationManager = (LocationManager) getActivity().
// getSystemService(getContext().LOCATION_SERVICE);
// Criteria criteria = new Criteria();
// Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
// if (location != null) {
// mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// new LatLng(location.getLatitude(), location.getLongitude()), 15.0f));
// // mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(),location.getLongitude())).title("hoodmark"));
//
// //Initialize Google Play Services
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(getActivity(),
// Manifest.permission.ACCESS_FINE_LOCATION)
// == PackageManager.PERMISSION_GRANTED) {
// buildGoogleApiClient();
// mGoogleMap.setMyLocationEnabled(true);
// }
// } else {
// buildGoogleApiClient();
// mGoogleMap.setMyLocationEnabled(true);
// }
//
// }
// new GetPostsDataTask().execute();
// }
#Override
public void onStart() {
super.onStart();
// mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
stopLocationUpdates();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getContext(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
/***
* Mango code to handle getting posts Top1000 in area based on likes
* as well as getting users location and
*/
/**
* TODO: query parse for the top 100 posts
* #param longitude
* #param latitude
* #return
*/
public ArrayList<ParseObject> getTop100PostsForLocation(double longitude, double latitude) {
ArrayList<ParseObject> top100Posts = new ArrayList<>();
return top100Posts;
}
LogCat:
java.lang.IllegalStateException: GoogleApiClient is not connected yet.
at com.google.android.gms.common.api.internal.zzj.zzb(Unknown Source)
at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
at com.mangoconcepts.hoodmarkandroid.fragments.MapTabFragment.startLocationUpdates(MapTabFragment.java:203)
at com.mangoconcepts.hoodmarkandroid.fragments.MapTabFragment.onConnected(MapTabFragment.java:184)
at com.google.android.gms.common.internal.zzk.zzk(Unknown Source)
at com.google.android.gms.common.api.internal.zzj.zzi(Unknown Source)
at com.google.android.gms.common.api.internal.zzh.zzpx(Unknown Source)
at com.google.android.gms.common.api.internal.zzh.onConnected(Unknown Source)
at com.google.android.gms.common.api.internal.zzl.onConnected(Unknown Source)
at com.google.android.gms.common.api.internal.zzc.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzg.zzqL(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzw(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzc.zzqN(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
you have to check your google Client api if its enabled or not . check this for more information :https://developers.google.com/api-client-library/java/google-api-java-client/android