*I am using GoogleApiClient to get current Location in my fragment.When I was test in API 22 Emulator It give Current Location perfect *
But
When I was tested In 23 Emulator Device It give 0 Location. when I was debug code I find onLocationChanged Method of com.google.android.gms.location.LocationListener Not called Why ?
Below is my code :
public class ContactUsFragment extends Fragment implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TAG", "OnCreate Called");
locationManager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
buildGoogleApiClient();
}
private synchronized void buildGoogleApiClient() {
Log.i("TAG", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void createLocationRequest() {
Log.i("TAG", "CreateLocationRequest");
mLocationRequest = new LocationRequest();
long UPDATE_INTERVAL = 10 * 1000;
mLocationRequest.setInterval(UPDATE_INTERVAL);
long FASTEST_INTERVAL = 10000;
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
}
*OnClick Listener Of imageview *
// ******************************** On Map Image Click Listener *************************************
ivMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("TAG", "On ImageView Click");
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, getActivity().getApplicationContext(), getActivity())) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
navigateToGoogleMap();
} else {
showSettingsAlert();
}
} else {
requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_REQUEST_CODE,getActivity());
}
} else {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
navigateToGoogleMap();
} else {
showSettingsAlert();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mGoogleApiClient != null)
mGoogleApiClient.disconnect();
}
#Override
public void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
Log.i("TAG", "On Start");
}
#Override
public void onDestroyView() {
super.onDestroyView();
Log.i("TAG", "On DestroyView");
}
#Override
public void onStop() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onPause() {
super.onPause();
// currentLocation.mGoogleApiClient.connect();
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
Log.i("TAG", "On Pause");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
Log.i("TAG","GoogleApiClient is Connected");
startLocationUpdates();
}
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public static void requestPermission(final String strPermission, final int perCode,final Activity _a) {
if (ActivityCompat.shouldShowRequestPermissionRationale(_a, strPermission)) {
Snackbar snackbar = Snackbar
.make(view.findViewById(R.id.fragment_contactus_linearlayout), "For Navigate we need Location Permission", Snackbar.LENGTH_LONG)
.setAction("Allow", new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(_a, new String[]{strPermission}, perCode);
}
});
snackbar.show();
} else {
ActivityCompat.requestPermissions(_a, new String[]{strPermission}, perCode);
}
}
public static boolean checkPermission(String strPermission, Context _c, Activity _a) {
int result = ContextCompat.checkSelfPermission(_c, strPermission);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
// ******************************** Get Permisson Request Result *************************************
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (PERMISSION_REQUEST_CODE == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Log.i("TAG", "Permission: " + permissions[0] + "was " + grantResults[0]);
//resume tasks needing this permission
Log.i("TAG", "Location Permission Granted");
startLocationUpdates();
navigateToGoogleMap();
// \n is for new line
Toast.makeText(getActivity().getApplicationContext(), "Your Location is - \nLat: " + currentlatitude + "\nLong: " + currentlongitude, Toast.LENGTH_LONG).show();
}
} else {
Log.i("TAG", "For Navigation Location Permisson is Required");
Toast.makeText(getActivity(), "Location Permission Not Granted", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle bundle) {
Location mCurrentLocation;
Log.i("TAG", "OnConnected");
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
currentlatitude = mCurrentLocation.getLatitude();
currentlongitude = mCurrentLocation.getLongitude();
}
// Begin polling for new location updates.
startLocationUpdates();
} else {
requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_REQUEST_CODE,getActivity());
}
} else {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
currentlatitude = mCurrentLocation.getLatitude();
currentlongitude = mCurrentLocation.getLongitude();
}
// Begin polling for new location updates.
startLocationUpdates();
}
}
private void startLocationUpdates() {
Log.i("TAG", "StartLocationUpdates");
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
} else {
requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_REQUEST_CODE,getActivity());
}
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
private void stopLocationUpdates() {
Log.i("TAG", "StopLocationUpdates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i("TAG", "onConnectionSuspended");
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(getActivity().getApplicationContext(), "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(getActivity().getApplicationContext(), "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Log.i("TAG", "OnLocationChanged");
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
currentlatitude = location.getLatitude();
currentlongitude = location.getLongitude();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(getActivity(), connectionResult.RESOLUTION_REQUIRED);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i("TAG", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
Related
This question already has answers here:
Error invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
(7 answers)
Closed 3 years ago.
when i click on current button for getting user's current location then give nullpointer exception even i check the fusedapi is granted or not and also when user allow for current location access then i retrive the current location but it show the error
MapFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_map, container, false);
latlng.add(new LatLng(22.32371, 73.16409));
latlng.add(new LatLng(22.32737, 73.17566));
latlng.add(new LatLng(22.28, 73.1903696));
latlng.add(new LatLng(22.334, 73.21853));
latlng.add(new LatLng(22.40303, 73.22369));
latlng.add(new LatLng(22.55148, 72.97035));
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(this);
askPermission();
createGoogleApi();
mbtn = rootview.findViewById(R.id.myLocationButton);
mbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getcurrentmarker();
}
});
return rootview;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mgoogleMap = googleMap;
mgoogleMap.setOnMarkerClickListener(this);
}
#Override
public void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
private void createGoogleApi()
{
Log.d(TAG, "createGoogleApi()");
if ( googleApiClient == null )
{
googleApiClient = new GoogleApiClient.Builder( getContext() )
.addConnectionCallbacks(this)
.addOnConnectionFailedListener( this )
.addApi(LocationServices.API)
.build();
}
}
// Check for permission to access Location
private boolean checkPermission() {
Log.d(TAG, "checkPermission()");
// Ask for permission if it wasn't granted yet
return (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// Asks for permission
private void askPermission() {
Log.d(TAG, "askPermission()");
ActivityCompat.requestPermissions(
MapFragment.super.getActivity(),
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION
);
}
// Verify user's response of the permission requested
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQ_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "Permission", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
// App cannot work without the permissions
private void permissionsDenied() {
Log.w(TAG, "permissionsDenied()");
}
// Start location Updates
private void startLocationUpdates(){
Log.i(TAG, "startLocationUpdates()");
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(6000)
.setFastestInterval(5000);
//movement in meter
if ( checkPermission() )
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged ["+location+"]");
lastLocation = location;
writeActualLocation(location);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "onConnected()");
getLastKnownLocation();
}
// GoogleApiClient.ConnectionCallbacks suspended
#Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "onConnectionSuspended()");
}
// GoogleApiClient.OnConnectionFailedListener fail
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.w(TAG, "onConnectionFailed()");
}
// Get last known location
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation()");
if ( checkPermission() ) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if ( lastLocation != null ) {
Log.i(TAG, "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w(TAG, "No location retrieved yet");
startLocationUpdates();
}
}
else askPermission();
}
private void writeActualLocation(Location location)
{
lastLocation = location;
showmarker(latlng);
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
private void getcurrentmarker()
{
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mgoogleMap.setMyLocationEnabled(true);
mgoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mgoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), 14));
}
private void showmarker(List<LatLng> positions)
{
Log.d(TAG,"show");
if(!markers.equals(null))
{
markers.clear();
}
if ( marker != null ) {
marker.remove();
}
for (LatLng position : positions) {
Marker marker = mgoogleMap.addMarker(
new MarkerOptions()
.position(position)
.visible(false)); // Invisible for now
markers.add(marker);
}
for (Marker marker : markers) {
if (SphericalUtil.computeDistanceBetween(new LatLng(lastLocation.getLatitude(),lastLocation.getLongitude()), marker.getPosition()) < 400) {
marker.setVisible(true);
float zoom = 14f;
CameraUpdate cameraUpdate1 = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), zoom);
mgoogleMap.animateCamera(cameraUpdate1);
}
}
}
#Override
public boolean onMarkerClick(Marker marker)
{
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment(lastLocation,marker.getPosition());
bottomSheetFragment.show(getFragmentManager(), bottomSheetFragment.getTag());
return false;
}
}
Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
before getting googleapiclient connected i ask the permission for current location then i retrive current location and after i click the current location button
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.eats.Fragment.MapFragment.getcurrentmarker(MapFragment.java:256)
Check for location is enabled/ disabled state
If location is disabled then result will be null.
I recommend using the FusedLocationProviderClient
Then doing something like this:
if (handleLocationPermission()) {
context?.let {
fusedLocationProvider = LocationServices.getFusedLocationProviderClient(it)
if (ContextCompat.checkSelfPermission(it, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider.lastLocation
.addOnSuccessListener { location ->
if (location != null) {
writeLastLocation(location.latitude, location.longitude)
}
}
}
}
}
}
```
I have implemented a way to retrieve the current location from Google Maps and it worked well.
But it does not work suddenly.
so I checked the code back into the past, but it still does not work.
I find what functions did not work, and I noticed that onLocationChanged() was not called.
I do not know what the problem is because no error message is displayed in the log.
This is the relevant code.
the code in a fragment with Google Maps
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
previous_marker = new ArrayList<>();
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_main, container, false);
ButterKnife.bind(this, rootView);
mActivity = getActivity();
mcontext = getContext();
Initialize();
mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
.enableAutoManage(mActivity, 1, this)
.addConnectionCallbacks(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.addApi(LocationServices.API)
.build();
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.googleMap);
mapFragment.getMapAsync(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL_MS);
locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);
other codes
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GPS_ENABLE_REQUEST_CODE:
if (checkLocationServicesStatus()) {
if (checkLocationServicesStatus()) {
if ( mGoogleApiClient.isConnected() == false ) {
Log.d( TAG, "onActivityResult : mGoogleApiClient connect ");
mGoogleApiClient.connect();
}
return;
}
}
break;
#Override
public void onLocationChanged(Location location) {
setCurrentLocation(location);
currentPosition = new LatLng(location.getLatitude(), location.getLongitude());
saveLat = location.getLatitude();
saveLng = location.getLongitude();
chooseLat = location.getLatitude();
chooseLng = location.getLongitude();
district = getDistrict(mcontext, location.getLatitude(), location.getLongitude());
getToken();
setDefaultPlace(location.getLatitude(), location.getLongitude());
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
if (!mRequestingLocationUpdates) startLocationUpdates();
}
if (askPermissionOnceAgain) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askPermissionOnceAgain = false;
checkPermissions();
}
}
}
private void startLocationUpdates() {
if (!checkLocationServicesStatus()) {
Log.d(TAG, "startLocationUpdates : call showDialogForLocationServiceSetting");
showDialogForLocationServiceSetting();
}else {
if (ActivityCompat.checkSelfPermission(mcontext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mcontext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
mRequestingLocationUpdates = true;
mGoogleMap.setMyLocationEnabled(false);
}
}
public boolean checkLocationServicesStatus() {
locationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
#Override
public void onStart() {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected() == false){
Log.d(TAG, "onStart: mGoogleApiClient connect");
mGoogleApiClient.connect();
}
if(!firstLoad){
mRequestingLocationUpdates = true;
}
super.onStart();
}
#Override
public void onStop() {
firstLoad = false;
if (mRequestingLocationUpdates) {
Log.d(TAG, "onStop : call stopLocationUpdates");
stopLocationUpdates();
}
if ( mGoogleApiClient.isConnected()) {
Log.d(TAG, "onStop : mGoogleApiClient disconnect");
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
if ( mRequestingLocationUpdates == false ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(mcontext,
android.Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(mActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
} else {
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
setDefaultLocation();
}
#Override
public void onConnectionSuspended(int cause) {
if (cause == CAUSE_NETWORK_LOST)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: network lost.");
else if (cause == CAUSE_SERVICE_DISCONNECTED)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: service disconnected");
}
and this is my permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If you know the reason or the wrong part of the code, I would appreciate it if you let me know.
Thank you for reading this article. Have a nice day
check these lines there in mapready method
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
// Setting event handler for location change
mMap.setOnMyLocationChangeListener(this);
}
Try to check if GPS is enabled on SDK 25.
Do this:
LocationManager manager = (LocationManager)
view.getContext().getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled =
manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
it always returns false. Then I start startActivityForResult as:
view.getFragment().startActivityForResult(intent,
Constants.GPS_ENABLE);
this opens me settings windows, I swtich GPS on, push back button, go back to fragment and got:
1. On Activity Result responsecode 0 (always)
2. GPS enabled checking again say "false", as it is not enabled.
Moreover, I tried this:
String provider =
Secure.getString(view.getContext().getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){}
And as google tutorial says task.locationsettings.
All tries always say GPS disabled and onActivityResult always 0.
I need both: know when GPS enabled/disaabled and recieve correct resultCode in onActivityResult(onActivityResult is called in Fragment and it is called succesfully, but with wrong responseCode in it)
What I do wrong?
UPDATE
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("ACTIVITY RESULT", "RqC:" + requestCode + "; ReSC" + resultCode);
if (requestCode == Constants.GPS_ENABLE && resultCode == RESULT_OK) {
presenter.getGPS();
} else {
Log.e("ON ACTIVITY RESULT", "Не дал мне прав");
}
}
public void onPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Constants.GPS_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getGPS();
}
default:
requestPermissions();
}
}
public void checkGpsEnabled(String caller) {
Log.e("I AM CALLED FROM", caller);
LocationManager manager = (LocationManager) view.getContext().getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGpsEnabled) {
Log.e("CheckGPSENABLED", "Включен");
getGPS();
} else {
Log.e("CheckGPSENABLED", "ВЫЫЫключен");
Toast.makeText(view.getContext(), "Для продолжения работы приложения, пожалуйста, включите GPS", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
view.getFragment().startActivityForResult(intent, Constants.GPS_ENABLE);
}
}
#SuppressLint("MissingPermission")
public void getGPS() {
Log.e(getClass().getName(), "getGPSFUSE");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(view.getViewActivity());
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(view.getViewActivity(), location -> {
if (location != null) {
Log.e("LOCATION", location.toString());
//Если получил координаты, вернуть
} else {
requestNewLocation();
}
});
}
#SuppressLint("MissingPermission")
public void requestNewLocation() {
Log.e(getClass().getName(), "request new location");
mLocationRequest = new LocationRequest();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Toast.makeText(view.getContext(), "Координаты не найдены", Toast.LENGTH_SHORT).show();
return;
}
for (Location location : locationResult.getLocations()) {
Log.e("NEW", location.toString());
}
}
};
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback,
null /* Looper */);
}
}
public void requestPermissions() {
if (ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(view.getViewActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET}, Constants.GPS_PERMISSION);
} else {
checkGpsEnabled("request");
}
}
I think you are too much confused in using FusedLocation API and GPS etc. Also in your question code snippet I dont see where you are acquiring runtime permission from user since your build target is 25. So you need to ask for some permissions. Like location permissions. here is a link of runtime permissions
Your manifest must contain these permissions and you must acquire run time permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Here the below code is for a quick over view. This snippet is taken from this link. And I think this link is also good for you.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
protected static final String TAG = "location-updates-sample";
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
private final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
private final static String LOCATION_KEY = "location-key";
private final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private static final int REQUEST_CHECK_SETTINGS = 10;
private ActivityMainBinding mBinding;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private Boolean mRequestingLocationUpdates;
private String mLastUpdateTime;
private String mLatitudeLabel;
private String mLongitudeLabel;
private String mLastUpdateTimeLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mLatitudeLabel = getResources().getString(R.string.latitude_label);
mLongitudeLabel = getResources().getString(R.string.longitude_label);
mLastUpdateTimeLabel = getResources().getString(R.string.last_update_time_label);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
buildGoogleApiClient();
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
Log.i(TAG, "Updating values from bundle");
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
setButtonsEnabledState();
}
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
updateUI();
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void startUpdatesButtonHandler(View view) {
clearUI();
if (!isPlayServicesAvailable(this)) return;
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
} else {
return;
}
if (Build.VERSION.SDK_INT < 23) {
setButtonsEnabledState();
startLocationUpdates();
return;
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
setButtonsEnabledState();
startLocationUpdates();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
showRationaleDialog();
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
}
public void stopUpdatesButtonHandler(View view) {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
setButtonsEnabledState();
stopLocationUpdates();
}
}
private void startLocationUpdates() {
Log.i(TAG, "startLocationUpdates");
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
break;
}
}
});
}
private void setButtonsEnabledState() {
if (mRequestingLocationUpdates) {
mBinding.startUpdatesButton.setEnabled(false);
mBinding.stopUpdatesButton.setEnabled(true);
} else {
mBinding.startUpdatesButton.setEnabled(true);
mBinding.stopUpdatesButton.setEnabled(false);
}
}
private void clearUI() {
mBinding.latitudeText.setText("");
mBinding.longitudeText.setText("");
mBinding.lastUpdateTimeText.setText("");
}
private void updateUI() {
if (mCurrentLocation == null) return;
mBinding.latitudeText.setText(String.format("%s: %f", mLatitudeLabel,
mCurrentLocation.getLatitude()));
mBinding.longitudeText.setText(String.format("%s: %f", mLongitudeLabel,
mCurrentLocation.getLongitude()));
mBinding.lastUpdateTimeText.setText(String.format("%s: %s", mLastUpdateTimeLabel,
mLastUpdateTime));
}
protected void stopLocationUpdates() {
Log.i(TAG, "stopLocationUpdates");
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setButtonsEnabledState();
startLocationUpdates();
} else {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
mRequestingLocationUpdates = false;
Toast.makeText(MainActivity.this, "このアプリの機能を有効にするには端末の設定画面からアプリの位置情報パーミッションを有効にして下さい。", Toast.LENGTH_SHORT).show();
} else {
showRationaleDialog();
}
}
break;
}
}
}
private void showRationaleDialog() {
new AlertDialog.Builder(this)
.setPositiveButton("許可する", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
})
.setNegativeButton("しない", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "位置情報パーミッションが許可されませんでした。", Toast.LENGTH_SHORT).show();
mRequestingLocationUpdates = false;
}
})
.setCancelable(false)
.setMessage("このアプリは位置情報の利用を許可する必要があります。")
.show();
}
public static boolean isPlayServicesAvailable(Context context) {
// Google Play Service APKが有効かどうかチェックする
int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
GoogleApiAvailability.getInstance().getErrorDialog((Activity) context, resultCode, 2).show();
return false;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
break;
}
break;
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
isPlayServicesAvailable(this);
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
#Override
protected void onStop() {
stopLocationUpdates();
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "onConnected");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
super.onSaveInstanceState(savedInstanceState);
}
}
I am coding to detect my current location in android marshmallow,but I am getting null location.Please tell any solution to resolve this problem.Google Map is working in my phone so why its returning null.
MainActivity.class
if (isGPSEnabled) {
if (location == null) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
if (mLocationManager != null) {
// mLocationManager.removeUpdates(locationListener);
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i("location","location-->"+location);
tv_new.setText("Location:" +String.valueOf(location));
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
tv_lat.setText("Latitude:" + String.valueOf(latitude));
tv_lon.setText("Longitude:" +String.valueOf(longitude));
String filterAddress = "";
try {
Log.i("TAG", "geoCoder" + geoCoder);
List<Address> addresses = geoCoder.getFromLocation(latitude, longitude, 1);
Log.i("TAG", "addresses" + addresses.size()+latitude+longitude);
for (int i = 0; i < addresses.get(0)
.getMaxAddressLineIndex(); i++) {
filterAddress += addresses.get(0).getAddressLine(i)
+ " ";
Log.i("TAG", "filterAddress" + filterAddress);
tv_address.setText("Address"+ filterAddress);
}
}
catch (IOException ex) {
Log.i("TAG", "filterAddress catch 1st"+ ex+ filterAddress);
ex.printStackTrace();
} catch (Exception e2) {
Log.i("TAG", "filterAddress catch 2nd"+e2+"--->"+geoCoder);
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
}
Output
Location:null in ASUS_ZOOLD Phone
Try like this ..
public class Splash extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> {
/** Define all global variables over here */
Context context;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
// All GPS based work goes over here ..
protected static final String TAG = "UserNavigation";
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected LocationSettingsRequest mLocationSettingsRequest;
protected Location mCurrentLocation;
protected Boolean mRequestingLocationUpdates = false;
protected String mLastUpdateTime;
private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
context = Splash.this;
SharedPrefUtil.setSharedPref(context, "alert", false);
new TestAsync().execute();
initui();
PulsatorLayout pulsator = (PulsatorLayout) findViewById(R.id.pulsator);
pulsator.start();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE}, PERMISSION_ACCESS_COARSE_LOCATION);
else
checkLocationSettings();
}
else
checkLocationSettings();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_ACCESS_COARSE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)
checkLocationSettings();
else
finish();
break;
}
}
private void initui() {
initiateSplashWork();
}
private void initiateSplashWork() {
if (checkPlayServices()) {
initiateGPS();
}
}
private void initiateGPS()
{
buildGoogleApiClient();
createLocationRequest();
buildLocationSettingsRequest();
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Toast.makeText(context, R.string.toast_device_not_support, Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
/** All GPS based method callback */
#Override
public void onConnected(Bundle bundle) {
Thread logoTimer = new Thread() {
public void run() {
try {
int logoTimer = 0;
while (logoTimer < 5000) {
sleep(100);
logoTimer = logoTimer + 100;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
logoTimer.start();
if (mCurrentLocation == null)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
return;
}
else
{
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
}
else
{
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
}
}
private void initiateNext()
{
Thread logoTimer = new Thread() {
public void run()
{
try
{
int logoTimer = 0;
while (logoTimer < 5000) {
sleep(100);
logoTimer = logoTimer + 100;
}
Intent intent = new Intent(context, OneClassBuilt.class);
startActivity(intent);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
finish();
}
}
};
logoTimer.start();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Toast.makeText(context, "onLocationChanged method : " + location.getLatitude() + " ____ " + location.getLongitude(), Toast.LENGTH_SHORT).show();
SharedPrefUtil.setSharedPref(context, "lat", String.valueOf(location.getLatitude()));
SharedPrefUtil.setSharedPref(context, "lon", String.valueOf(location.getLongitude()));
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
}
protected void checkLocationSettings() {
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, mLocationSettingsRequest);
result.setResultCallback(this);
}
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
startLocationUpdates();
initiateNext();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings ");
try {
status.startResolutionForResult(Splash.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
finish();
Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created.");
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
startLocationUpdates();
initiateNext();
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
finish();
break;
}
break;
}
}
protected void startLocationUpdates() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
mRequestingLocationUpdates = true;
}
});
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
mRequestingLocationUpdates = false;
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected() && mRequestingLocationUpdates)
startLocationUpdates();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
stopLocationUpdates();
}
#Override
protected void onStop() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
} // End of main class over here ..
In Manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
And in App gradle file over dependency add..
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.google.android.gms:play-services-location:8.1.0'
Add this code to ask for permission
`
private void checkForPermisson {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 202);
}
return;
} else {
//add your if block here
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 202:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//add your if block here
} else {
Log.e(TAG, "else RequestPermission");
}
break;
default:
return;
}
}
`
im trying to get the city and country from a location but i am catchinf an exception : GoogleApiClient is not connected yet
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);`
`if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
}
displayLocation();
togglePeriodicLocationUpdates();}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
city = address.get(0).getLocality();
country = address.get(0).getCountryName();
} catch (IOException e) {
} catch (NullPointerException e) {
}
} else {
Toast.makeText(this, "erreur", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnected(Bundle bundle) {
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
private void togglePeriodicLocationUpdates() {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
// Starting the location updates
startLocationUpdates();
Log.d(TAG, "Periodic location updates started!");
} else {
// Changing the button text
mRequestingLocationUpdates = false;
// Stopping the location updates
stopLocationUpdates();
Log.d(TAG, "Periodic location updates stopped!");
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT); // 10 meters
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
does anyone know why i am getting this Exception , because i already connected the api in the onStart() method !!
any answer would be helpful :D
onCreate() gets called before onStart(), so you are requesting the location before you have connected to the Google API.
Here is the lifecycle diagram from the Android Dev site: http://developer.android.com/reference/android/app/Activity.html