Skip to content Skip to sidebar Skip to footer

Current Location Failed Googlemap

I want to check if the GPS is on if it is should show the current location. If not it should ask to turn it on. If user click cancel or dont turn the coordinates will be set as bas

Solution 1:

This requires a lot of case handling and I am providing a complete implementation of the all the features you requested with brief explanations below.

1. Provide location permission in the manifest

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

2. Add location dependency in app's build.gradle

compile'com.google.android.gms:play-services-location:9.2.1'

3. extend BroadcastReceiver and create GPSStatusReceiver

publicclassGPSStatusReceiverextendsBroadcastReceiver {

    private GpsStatusChangeListener mCallback;
    private Context mContext;

    publicGPSStatusReceiver(Context context, GpsStatusChangeListener callback) {
        mCallback = callback;
        mContext = context;

        IntentFilterintentFilter=newIntentFilter();
        intentFilter.addAction("android.location.PROVIDERS_CHANGED");
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        context.registerReceiver(this, intentFilter);
    }

    publicvoidunRegisterReceiver(){
        Log.d("ali", "unRegisterReceiver");
        mContext.unregisterReceiver(this);
    }

    @OverridepublicvoidonReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Log.d("ali", "in PROVIDERS_CHANGED");
            mCallback.onGpsStatusChange();
        }
    }

    publicinterfaceGpsStatusChangeListener{
        voidonGpsStatusChange();
    }
}

4. Create a class GPSLocation

publicclassGPSLocationimplementsConnectionCallbacks,
        OnConnectionFailedListener,
        LocationListener,
        GPSStatusReceiver.GpsStatusChangeListener {

    publicstaticfinalintREQUEST_CHECK_SETTINGS=100;
    publicstaticfinalintLOCATION_PERMISSION_REQUEST_CODE=200;

    privatestaticfinalintPERMISSION_GRANTED=0;
    privatestaticfinalintPERMISSION_DENIED=1;
    privatestaticfinalintPERMISSION_BLOCKED=2;

    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private LocationCallback mCallback;
    private Activity mActivity;
    private Context mContext;
    private LocationRequest mLocationRequest;
    private GPSStatusReceiver mGPSStatusReceiver;

    privatelongintervalMillis=10000;
    privatelongfastestIntervalMillis=5000;
    privateintaccuracy= LocationRequest.PRIORITY_HIGH_ACCURACY;

    privatebooleanisInitialized=false;
    privatebooleanisLocationEnabled=false;
    privatebooleanisPermissionLocked=false;

    publicGPSLocation(Activity activity, LocationCallback callback) {
        mActivity = activity;
        mContext = activity.getApplicationContext();
        mCallback = callback;
        if (mGoogleApiClient == null) {
            mGoogleApiClient = newGoogleApiClient.Builder(mContext)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        createLocationRequest();
        mGPSStatusReceiver = newGPSStatusReceiver(mContext, this);
    }


    publicvoidinit(){
        isInitialized = true;
        if(mGoogleApiClient != null) {
            if (mGoogleApiClient.isConnected()) {
                requestPermission();
            } else {
                connect();
            }
        }
    }


    publicvoidcreateLocationRequest() {
        mLocationRequest = newLocationRequest();
        mLocationRequest.setInterval(intervalMillis);
        mLocationRequest.setFastestInterval(fastestIntervalMillis);
        mLocationRequest.setPriority(accuracy);
    }


    public LocationRequest getLocationRequest() {
        return mLocationRequest;
    }


    publicvoidconnect(){
        if(mGoogleApiClient != null && isInitialized) {
            mGoogleApiClient.connect();
        }
    }


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


    privatevoidgetLastKnownLocation(){
        if(!mGoogleApiClient.isConnected()){
            Log.d("ali", "getLastKnownLocation restart ");
            mGoogleApiClient.connect();
        }
        else {
            if (checkLocationPermission(mContext) && isLocationEnabled) {
                Log.d("ali", "getLastKnownLocation read ");
                if(mCurrentLocation == null) {
                    mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    mCallback.onLastKnowLocationFetch(mCurrentLocation);
                }
                startLocationUpdates();
            }else{
                Log.d("ali", "getLastKnownLocation get permission ");
                requestPermission();
            }
        }
        Log.d("ali", "mCurrentLocation " + mCurrentLocation);
    }


    publicvoidstartLocationUpdates() {
        if(checkLocationPermission(mContext)
                && mGoogleApiClient != null
                && mGoogleApiClient.isConnected()
                && isLocationEnabled) {
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        }
    }


    publicvoidstopLocationUpdates() {
        if(mGoogleApiClient != null
                && mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);
        }
    }


    @OverridepublicvoidonConnected(@Nullable Bundle bundle) {
        Log.d("ali", "onConnected");
        requestPermission();
    }


    @OverridepublicvoidonConnectionSuspended(int i) {
        Log.d("ali", "onConnectionSuspended");
    }


    @OverridepublicvoidonConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d("ali", "onConnectionFailed");
    }


    @OverridepublicvoidonLocationChanged(Location location) {
        Log.d("ali", "onLocationChanged : " + location);
        mCallback.onLocationUpdate(location);
    }


    @OverridepublicvoidonGpsStatusChange() {
        Log.d("ali", "onGpsStatusChange");
        if(isInitialized && !isPermissionLocked) {
            if (!isLocationEnabled(mContext)) {
                isLocationEnabled = false;
                isPermissionLocked = true;
                stopLocationUpdates();
                requestPermission();
            }
        }
    }


    privatevoidrequestPermission(){
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){
            String[] appPerm = newString[]{Manifest.permission.ACCESS_FINE_LOCATION};
            ActivityCompat.requestPermissions(mActivity, appPerm, LOCATION_PERMISSION_REQUEST_CODE);
        }else{
            getLocationSetting();
        }
    }


    publicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
            if (resultCode == Activity.RESULT_OK) {
                getLastKnownLocation();
            }else{
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
                mCallback.onLocationSettingsError();
            }
        }
    }


    privatevoidgetLocationSetting(){
        LocationSettingsRequest.Builderbuilder=newLocationSettingsRequest
                        .Builder()
                        .addLocationRequest(mLocationRequest);

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

        result.setResultCallback(newResultCallback<LocationSettingsResult>(){
            @OverridepublicvoidonResult(LocationSettingsResult result) {
                finalStatusstatus= result.getStatus();
                finalLocationSettingsStateslocationSettingsStates= result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.d("ali", "SUCCESS");
                        isLocationEnabled = true;
                        isPermissionLocked = false;
                        getLastKnownLocation();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.d("ali", "RESOLUTION_REQUIRED");
                        try {
                            status.startResolutionForResult(
                                    mActivity,
                                    REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                            mCallback.onLocationSettingsError();
                        }finally {
                            isPermissionLocked = false;
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.d("ali", "SETTINGS_CHANGE_UNAVAILABLE");
                        Toast.makeText(mContext, "Location Unavailable", Toast.LENGTH_SHORT).show();
                        mCallback.onLocationSettingsError();
                        isPermissionLocked = false;
                        break;
                }
            }
        });

    }


    publicvoidonRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        int permState;
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0) {
                    if(grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        if(!ActivityCompat.shouldShowRequestPermissionRationale(
                                mActivity,
                                Manifest.permission.ACCESS_FINE_LOCATION)){
                            permState = PERMISSION_BLOCKED;
                        }else{permState = PERMISSION_DENIED;}
                    }else {permState = PERMISSION_GRANTED;}
                }
                else{permState = PERMISSION_DENIED;}

                switch (permState){
                    case PERMISSION_BLOCKED:
                        Toast.makeText(mContext,"Please give gps location permission to use the app.",Toast.LENGTH_LONG).show();
                        startInstalledAppDetailsActivity(mContext);
                        mCallback.onLocationPermissionDenied();
                        break;
                    case PERMISSION_DENIED:
                        Toast.makeText(mContext,"Permission Denied, app cannot access the gps location.", Toast.LENGTH_LONG).show();
                        break;
                    case PERMISSION_GRANTED:
                        getLocationSetting();
                        break;
                }
                break;
        }
    }

    publicstaticbooleanisLocationEnabled(Context context){
        LocationManagerlocationManager= (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        booleangpsEnabled=false;
        booleannetworkEnabled=false;

        try {
            gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch(Exception ex) {}

        try {
            networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch(Exception ex) {}

        return gpsEnabled && networkEnabled;
    }

    publicstaticvoidstartInstalledAppDetailsActivity(final Context context) {
        if (context == null) {
            return;
        }
        finalIntenti=newIntent();
        i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.setData(Uri.parse("package:" + context.getPackageName()));
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(i);
    }

    publicstaticbooleancheckLocationPermission(Context context) {
        Stringpermission="android.permission.ACCESS_FINE_LOCATION";
        intres= context.checkCallingOrSelfPermission(permission);
        return (res == PackageManager.PERMISSION_GRANTED);
    }

    publicinterfaceLocationCallback {
        voidonLastKnowLocationFetch(Location location);
        voidonLocationUpdate(Location location);
        voidonLocationPermissionDenied();
        voidonLocationSettingsError();
    }


    publicvoidclose() {
        mGPSStatusReceiver.unRegisterReceiver();
    }
}

5. In the activity use the below code

publicclassMainActivityextendsAppCompatActivityimplementsGPSLocation.LocationCallback {

    privateGPSLocation mGPSLocation;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGPSLocation = newGPSLocation(this, this);
        mGPSLocation.init();
    }

    @OverridepublicvoidonLastKnowLocationFetch(Location location) {
        if(location != null) {
            Log.d("ali ", "onLastKnowLocationFetch " + location);
        }
    }

    @OverridepublicvoidonLocationUpdate(Location location) {
        if(location != null) {
            Log.d("ali ", "onLocationUpdate " + location);
        }
    }

    @OverridepublicvoidonLocationPermissionDenied() {

    }

    @OverridepublicvoidonLocationSettingsError() {

    }

    @OverrideprotectedvoidonStart() {
        mGPSLocation.connect();
        super.onStart();
    }


    @OverridepublicvoidonResume() {
        super.onResume();
        mGPSLocation.startLocationUpdates();
    }


    @OverrideprotectedvoidonPause() {
        super.onPause();
        mGPSLocation.stopLocationUpdates();
    }


    @OverrideprotectedvoidonStop() {
        mGPSLocation.disconnect();
        super.onStop();
    }


    @OverrideprotectedvoidonDestroy() {
        mGPSLocation.close();
        super.onDestroy();
    }


    @OverridepublicvoidonRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == GPSLocation.LOCATION_PERMISSION_REQUEST_CODE) {
            mGPSLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @OverridepublicvoidonActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
            mGPSLocation.onActivityResult(requestCode, resultCode, data);
        }
    }
}

Solution 2:

The following code checks, if location is enabled or not. If not it shows alert dialog to enable location service.

LocationManagerlm= (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
    AlertDialog.Builderdialog=newAlertDialog.Builder(this);
    dialog.setMessage(getResources().getString(R.string.gps_network_not_enabled));
    dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), newDialogInterface.OnClickListener() {
        @OverridepublicvoidonClick(DialogInterface paramDialogInterface, int paramInt) {                 
            IntentmyIntent=newIntent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            Startup.this.startActivity(myIntent);                    
        }
    });
    dialog.setNegativeButton(getString(R.string.Cancel), newDialogInterface.OnClickListener() {

        @OverridepublicvoidonClick(DialogInterface paramDialogInterface, int paramInt) {
            // TODO Auto-generated method stub

        }
    });
    dialog.show();
}

add below code in AndroidManifest.xml

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

Solution 3:

Add this override method for me its worked fine--

@OverridepublicvoidonLocationChanged(Location location) {
    getLocation("onLocationChanged");
}

Post a Comment for "Current Location Failed Googlemap"