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);
}
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)
}
}
}
}
}
}
```
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'm using mapbox in my mobile to fetch the current location but sometimes it's showing the marker and in logcat its showing as java.lang.IllegalStateException: GoogleApiClient is not connected yet.
Note when I click that line in logcat it goes to this code
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
REQUEST,
this); // LocationListener
}
This is my java code:
public class ClockInDetails extends Fragment implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
private MapboxMap mMapBoxMap;
private GoogleApiClient mGoogleApiClient = null;
private LatLng gs_var_mLatLng;
private MarkerOptions mMarker;
LocationRequest mLocationRequest;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000)
.setFastestInterval(5000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
public ClockInDetails() {
// Required empty public constructor
}
public static boolean isGPSEnabled = false;
public static boolean isNetworkEnabled = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Mapbox.getInstance(getContext(), getString(R.string.access_token));
View view = inflater.inflate(R.layout.fragment_clock_in_details, container, false);
try {
gs_mapView = (MapView)view.findViewById(R.id.gs_mapView);
//to check gps is enabled or not
gs_mapView.onCreate(savedInstanceState);
//mapbox view to display current locations by calling buildgooglepaiclient
gs_mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
mMapBoxMap = mapboxMap;
buildGoogleApiClient();
mapboxMap.setMyLocationEnabled(true);
}
});
locationManager = (LocationManager) getContext().getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.layout_confirmation);
TextView tv_alert_Message = (TextView) dialog.findViewById(R.id.message);
tv_alert_Message.setText("GPS has been disabled in your device. Please enable it?");
Button btn_submit = (Button) dialog.findViewById(R.id.ok);
Button btn_cancel = (Button) dialog.findViewById(R.id.cancel);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getContext().startActivity(callGPSSettingIntent);
buildGoogleApiClient();
dialog.dismiss();
}
});
dialog.show();
} else {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
#Override
public void onStart() {
super.onStart();
gs_mapView.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
public void onResume() {
super.onResume();
gs_mapView.onResume();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
public void onPause() {
try {
super.onPause();
gs_mapView.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
gs_mapView.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
gs_mapView.onLowMemory();
}
#Override
public void onDestroy() {
super.onDestroy();
gs_mapView.onDestroy();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
gs_mapView.onSaveInstanceState(outState);
}
private synchronized void buildGoogleApiClient() {
try {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
private void GS_Funtcion_updateCamera() {
try {
CameraPosition position = new CameraPosition.Builder()
.target(gs_var_mLatLng) // Sets the new camera position
.zoom(16) // Sets the zoom
.bearing(0) // Rotate the camera
.tilt(0) // Set the camera tilt
.build(); // Creates a CameraPosition from the builder
mMapBoxMap.animateCamera(CameraUpdateFactory
.newCameraPosition(position), 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void GS_Funtcion_updateMarker() {
try {
mMapBoxMap.clear();
mMarker = new MarkerOptions()
.position(gs_var_mLatLng)
.title("Location")
.snippet("Welcome to you")
.icon(drawableToIcon(getContext(),ServerUtils.Gs_ImagePath+gs_var_user_image, 1));
mMapBoxMap.addMarker(mMarker);
} catch (Exception e) {
e.printStackTrace();
}
}
private void GS_Funtcion_addMarker() {
try {
gs_var_latitude = gs_var_mLatLng.getLatitude();
gs_var_longitude = gs_var_mLatLng.getLongitude();
mMarker = new MarkerOptions()
.position(gs_var_mLatLng)
.title("Location")
.snippet("Welcome to you")
.icon(drawableToIcon(getContext(),ServerUtils.Gs_ImagePath+gs_var_user_image, 1));
mMapBoxMap.addMarker(mMarker);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
try {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
REQUEST,
this); // LocationListener
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
try {
Log.i("SS","loca--"+location);
gs_var_mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
GS_Funtcion_updateCamera();
if (mMarker != null) {
Log.i("SS","if---loca--"+location);
GS_Funtcion_updateMarker();
}else{
GS_Funtcion_addMarker();
Log.i("SS","else---loca--"+location);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], 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) {
if (ContextCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
}
} else {
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
I don't know why it's not showing even though the location is On, I connected the googleApiClient in onStart(), onResume() but why its showing not connected yet.Marker is not showing on the map.Please help me someone.
In Android 4.4 I have one alert to check gps is enable or not that popup is not showing.Please help me, what mistake I did, But sometimes marker its showing how?
logcat-image
Before applying mGoogleApiClient.connect(); you should add a null check i.e. your code should look like this:
if(mGoogleApiClient!=null)
mGoogleApiClient.connect();
I am using Fused Location Api for getting the latitude and longitude.It's mentioned in the documents that it uses GPS, Wifi and network(Cell) to return the most accurate location of the user. I've a couple of questions here:
1)I've noticed that if I turn off the wifi, it still gives the result but it gives null when GPS is turned off, why is that? Isn't it suppose to use the Wifi to give the location detail even if gps is off or not available? P.S. I've used ACCESS_FINE_LOCATION for permission.
2)How can I know/test whether the location detail is returned using Wifi or GPS or network (Cell tower)?
3)Will it work using network (cell tower) when both GPS and wifi are off?
Fused Location Provider code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
if (checkPlayServices()) {
Log.i("playservice", checkPlayServices()+"");
// Building the GoogleApi client
buildGoogleApiClient();
}
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
}
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
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;
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "GoogleApiClient connected!");
createLocationRequest();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.i(TAG, " Location: " + mLastLocation);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(final LocationResult locationResult) {
Log.i("onLocationResult",locationResult + "");
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lblLocation.setText(locationResult.getLocations() + "");
}
});
}
#Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
Log.i("onLocationAvailability", "onLocationAvailability: isLocationAvailable = " + locationAvailability.isLocationAvailable());
}
}, null);
}
#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();
Log.i(TAG, "mGoogleApiClient.connect()");
}
}
When I've GPS on, the output I get is:
I/onLocationResult(7481): LocationResult[locations: [Location[fused 27.673576,85.314083 acc=16 et=+1d1h59m30s347ms alt=1289.0999755859375 vel=0.93 bear=166.0]]]
*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());
}
}