Example usage for android.location LocationManager NETWORK_PROVIDER

List of usage examples for android.location LocationManager NETWORK_PROVIDER

Introduction

In this page you can find the example usage for android.location LocationManager NETWORK_PROVIDER.

Prototype

String NETWORK_PROVIDER

To view the source code for android.location LocationManager NETWORK_PROVIDER.

Click Source Link

Document

Name of the network location provider.

Usage

From source file:biz.bokhorst.bpt.BPTService.java

protected synchronized void startLocating() {
    // Start activity recognition
    if (activityRecognitionClient == null)
        activityRecognitionClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API)
                .addConnectionCallbacks(BPTService.this).build();

    // Connect activity recognition
    if (!activityRecognitionClient.isConnected() && !activityRecognitionClient.isConnecting()) {
        sendActivity(getString(R.string.connecting), -1, new Date().getTime());
        activityRecognitionClient.connect();
    }/*from ww w . java 2 s  .co m*/

    // Schedule next alarm
    long interval = Integer.parseInt(
            preferences.getString(Preferences.PREF_TRACKINTERVAL, Preferences.PREF_TRACKINTERVAL_DEFAULT)) * 60L
            * 1000L;
    long alarmTime = SystemClock.elapsedRealtime() + interval;
    alarmManager.cancel(pendingAlarmIntent);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingAlarmIntent);

    // Prepare user feedback
    nextTrackTime = new Date(System.currentTimeMillis() + interval);

    // Use activity recognition?
    boolean recognition = preferences.getBoolean(Preferences.PREF_ACTIVITYRECOGNITION,
            Preferences.PREF_ACTIVITYRECOGNITION_DEFAULT);

    if (recognition && !should)
        sendStage(String.format(getString(R.string.StageStill), TIME_FORMATTER.format(nextTrackTime)));

    if (!locating && (recognition ? should || once : true)) {
        locating = true;
        locationwait = false;
        wakeLock.acquire();

        // Start waiting for fix
        long timeout = Integer.parseInt(
                preferences.getString(Preferences.PREF_FIXTIMEOUT, Preferences.PREF_FIXTIMEOUT_DEFAULT))
                * 1000L;
        taskHandler.postDelayed(FixTimeoutTask, timeout);

        // Request location updates
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this,
                taskHandler.getLooper());
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this,
                taskHandler.getLooper());
        locationManager.addGpsStatusListener(this);

        // User feedback
        Date timeoutTime = new Date(System.currentTimeMillis() + timeout);
        boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        sendStage(String.format(getString(R.string.StageFixWait), TIME_FORMATTER.format(timeoutTime)));
        sendStatus(gpsEnabled ? getString(R.string.On) : getString(R.string.Off));
        sendSatellites(-1, -1);
    }
}

From source file:org.wso2.edgeanalyticsservice.LocationSystemService.java

/** Initialize the location system Service and set the minimal update distance and time  */
public void startLocationService(Context context) {
    mContext = context;/*www  . j  av  a  2s  .c  om*/
    mLocationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);
    Criteria locationCritera = new Criteria();
    locationCritera.setAccuracy(Criteria.ACCURACY_COARSE);
    locationCritera.setAltitudeRequired(false);
    locationCritera.setBearingRequired(false);
    locationCritera.setCostAllowed(true);
    locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);

    String providerName = mLocationManager.getBestProvider(locationCritera, true);

    if (providerName != null && mLocationManager.isProviderEnabled(providerName)) {
        if (ActivityCompat.checkSelfPermission(mContext,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public
            // void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.e("Location", "No permission");
            return;
        }
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES,
                (float) MINIMUM_DISTANCE_FOR_UPDATES, new MyLocationListner(), Looper.getMainLooper());
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES,
                (float) MINIMUM_DISTANCE_FOR_UPDATES, new MyLocationListner(), Looper.getMainLooper());
        mlocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        //        mTaskManager.sendLocationData(new double[]{mlocation.getLatitude(), mlocation.getLongitude()});
        mLocationListner = new MyLocationListner();
        synchronized (this) {
            started = true;
        }
    } else {
        // Provider not enabled, prompt user to enable it
        Toast.makeText(mContext, "Please turn on GPS", Toast.LENGTH_LONG).show();
        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(myIntent);
    }
}

From source file:org.iransoil.collect.android.activities.GeoPointMapActivitySdk7.java

@Override
protected void onResume() {
    super.onResume();
    if (mCaptureLocation) {
        ((MyLocationOverlay) mLocationOverlay).enableMyLocation();
        if (mGPSOn) {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }/* ww w .  ja  v a 2s .  co  m*/
        if (mNetworkOn) {
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }
    }
}

From source file:org.mapsforge.applications.android.samples.location.MyLocationOverlay.java

private void enableBestAvailableProviderPermissionGranted() {
    disableMyLocation();// www .  ja  v  a  2 s .  com

    this.circle.setDisplayModel(this.displayModel);
    this.marker.setDisplayModel(this.displayModel);

    boolean result = false;
    for (String provider : this.locationManager.getProviders(true)) {
        if (LocationManager.GPS_PROVIDER.equals(provider)
                || LocationManager.NETWORK_PROVIDER.equals(provider)) {
            result = true;
            this.locationManager.requestLocationUpdates(provider, minTime, minDistance, this);
        }
    }
    this.myLocationEnabled = result;
}

From source file:com.smsc.usuario.ui.MapaActivity.java

public void getLocation() {
    try {/*from   w  ww .j  av  a  2 s. co  m*/
        locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
            Toast.makeText(this, "Por favor Active su GPS", Toast.LENGTH_SHORT).show();
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        onLocationChanged(location);
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            onLocationChanged(location);
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.voidsink.anewjkuapp.base.MyLocationOverlay.java

private void enableBestAvailableProviderPermissionGranted() {
    disableMyLocation();/*  w w  w .  j  a  va 2  s.  c  om*/

    this.circle.setDisplayModel(this.displayModel);
    this.marker.setDisplayModel(this.displayModel);

    boolean result = false;
    if (ActivityCompat.checkSelfPermission(this.activity,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        for (String provider : this.locationManager.getProviders(true)) {
            if (LocationManager.GPS_PROVIDER.equals(provider)
                    || LocationManager.NETWORK_PROVIDER.equals(provider)) {
                result = true;
                this.locationManager.requestLocationUpdates(provider, minTime, minDistance, this);
            }
        }
    }
    this.myLocationEnabled = result;
}

From source file:com.patil.geobells.lite.MainActivity.java

public void checkLocationServicesEnabled() {
    LocationManager lm = null;//from  w w w  .j  a v  a 2 s  .  c o m
    boolean gps_enabled = true, network_enabled = true;
    if (lm == null)
        lm = (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.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_enable_locationservices);
        dialog.setMessage(getString(R.string.dialog_message_enable_locationservices));
        dialog.setCancelable(false);
        dialog.setPositiveButton(getString(R.string.dialog_button_open_location_settings),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        paramDialogInterface.dismiss();
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    }
                });
        dialog.setNegativeButton(getString(R.string.dialog_button_nothanks),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        finish();
                    }
                });
        dialog.create().show();

    }
}

From source file:com.warp10.app.LocationService.java

/**
 * Handler of action Start//  w w w.  java  2  s . co m
 * @param isListenGPS if asked register GPS
 * @param isListenNetWork if asked register Network location
 */
private void handleActionStart(boolean isListenGPS, boolean isListenNetWork, final Context context,
        boolean recGPS, boolean recNetwork, final String prefixGTS) {
    // Define a listener that responds to location updates

    if (isRunning) {
        this.onDestroy();
    }
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    final boolean record = recGPS || recNetwork;

    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (record) {
                //Log.d("GPSLOCA",location.toString());
                long timestamp = System.currentTimeMillis() * 1000;
                // If buffer have full size
                if (null == stringBuffer) {
                    stringBuffer = new StringBuffer();
                }
                if (stringBuffer.length() >= BUFFER_SIZE) {
                    emptyBuffer();
                }
                if (stringBuffer.length() > 0) {
                    stringBuffer.append("\n");
                }
                String fix = "";
                /**
                 if(prefixGTS.equals(new String()))
                 {
                 prefixGTS = "android";
                 }*/
                if (prefixGTS.length() != prefixGTS.lastIndexOf(".")) {
                    fix = ".";
                }
                String string = timestamp + "/" + location.getLatitude() + ":" + location.getLongitude() + "/ "
                        + prefixGTS + fix + location.getProvider() + "{" + "source=android" + "} true";
                stringBuffer.append(string);
                //Log.d("Location Handler", stringBuffer.toString());
            }
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            //emptyBuffer();
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
            emptyBuffer();
        }

        /**
         * empty current buffer
         */
        public void emptyBuffer() {
            if (null != stringBuffer) {
                //Log.d("LocationService", stringBuffer.toString());
                final StringBuffer buffer = new StringBuffer(stringBuffer);
                if (CollectService.isPostActive) {
                    FileService.writeToFile(buffer.toString(), context);
                } else {
                    if (CollectService.ws.isClosed()) {
                        FileService.writeToFile(buffer.toString(), context);
                    } else {
                        List<File> allFiles = FileService.getAllFiles("fill", context, true);
                        for (File file : allFiles) {
                            String data = FileService.readMetricFile(file);
                            if (CollectService.ws.writeData(data)) {
                                file.delete();
                            }
                        }
                        if (!CollectService.ws.writeData(buffer.toString())) {
                            FileService.writeToFile(buffer.toString(), context);
                        }
                    }
                }
                stringBuffer = new StringBuffer();
            }
        }
    };

    // Register the listener with the Location Manager to receive location updates
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    if (isListenGPS || recGPS) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, locationListener);
        setLocManager();
    }
    if (isListenNetWork || recNetwork) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, locationListener);
        setLocManager();
    }
    //Log.d("LOCATIONB", locationManager.getAllProviders().toString());
    //Log.d("LOCATIONB", locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).toString());
    isRunning = true;

}

From source file:fr.univsavoie.ltp.client.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Appliquer le thme LTP a l'ActionBar
    //setTheme(R.style.Theme_ltp);

    // Cration de l'activit principale
    setContentView(R.layout.activity_main);

    // Instancier les classes utiles
    setPopup(new Popup(this));
    setSession(new Session(this));
    setTools(new Tools(this));

    // Afficher la ActionBar
    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setHomeButtonEnabled(true);
    mActionBar.setDisplayShowHomeEnabled(true);

    // MapView settings
    map = (MapView) findViewById(R.id.openmapview);
    map.setTileSource(TileSourceFactory.MAPNIK);
    map.setBuiltInZoomControls(false);//from   w  ww .  j  ava2  s.c  o m
    map.setMultiTouchControls(true);

    // MapController settings
    mapController = map.getController();

    //To use MapEventsReceiver methods, we add a MapEventsOverlay:
    overlay = new MapEventsOverlay(this, this);
    map.getOverlays().add(overlay);

    boolean isWifiEnabled = false;
    boolean isGPSEnabled = false;

    // Vrifier si le wifi ou le rseau mobile est activ
    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (wifi.isAvailable() && (wifi.getDetailedState() == DetailedState.CONNECTING
            || wifi.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_wifi, Toast.LENGTH_LONG).show();
        isWifiEnabled = true;
    } else if (mobile.isAvailable() && (mobile.getDetailedState() == DetailedState.CONNECTING
            || mobile.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_3G, Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, R.string.toast_aucun_reseau, Toast.LENGTH_LONG).show();
    }

    // Obtenir le service de localisation
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // Verifier si le service de localisation GPS est actif, le cas echeant, tester le rseau
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        isGPSEnabled = true;
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    // Afficher une boite de dialogue et proposer d'activer un ou plusieurs services pas actifs
    if (!isWifiEnabled || !isGPSEnabled) {
        //getTools().showSettingsAlert(this, isWifiEnabled, isGPSEnabled);
    }

    // Si on a une localisation, on dfinit ses coordonnes geopoint
    if (location != null) {
        startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
    } else {
        // Sinon, on indique des paramtres par dfaut
        location = getTools().getLastKnownLocation(locationManager);
        if (location == null) {
            location = new Location("");
            location.setLatitude(46.227638);
            location.setLongitude(2.213749000000);
        }
        startPoint = new GeoPoint(46.227638, 2.213749000000);
    }

    setLongitude(location.getLongitude());
    setLatitude(location.getLatitude());

    destinationPoint = null;
    viaPoints = new ArrayList<GeoPoint>();

    // On recupre quelques paramtres de la session prcdents si possible
    if (savedInstanceState == null) {
        mapController.setZoom(15);
        mapController.setCenter(startPoint);
    } else {
        mapController.setZoom(savedInstanceState.getInt("zoom_level"));
        mapController.setCenter((GeoPoint) savedInstanceState.getParcelable("map_center"));
    }

    // Crer un overlay sur la carte pour afficher notre point de dpart
    myLocationOverlay = new SimpleLocationOverlay(this, new DefaultResourceProxyImpl(this));
    map.getOverlays().add(myLocationOverlay);
    myLocationOverlay.setLocation(startPoint);

    // Boutton pour zoomer la carte
    ImageButton btZoomIn = (ImageButton) findViewById(R.id.btZoomIn);
    btZoomIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomIn();
        }
    });

    // Boutton pour dezoomer la carte
    ImageButton btZoomOut = (ImageButton) findViewById(R.id.btZoomOut);
    btZoomOut.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomOut();
        }
    });

    // Pointeurs d'itinrairea:
    final ArrayList<ExtendedOverlayItem> waypointsItems = new ArrayList<ExtendedOverlayItem>();
    itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, waypointsItems, map,
            new ViaPointInfoWindow(R.layout.itinerary_bubble, map));
    map.getOverlays().add(itineraryMarkers);
    //updateUIWithItineraryMarkers();

    Button searchButton = (Button) findViewById(R.id.buttonSearch);
    searchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            handleSearchLocationButton();
        }
    });

    //context menu for clicking on the map is registered on this button. 
    registerForContextMenu(searchButton);

    // Routes et Itinraires
    final ArrayList<ExtendedOverlayItem> roadItems = new ArrayList<ExtendedOverlayItem>();
    roadNodeMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, map);
    map.getOverlays().add(roadNodeMarkers);

    if (savedInstanceState != null) {
        mRoad = savedInstanceState.getParcelable("road");
        updateUIWithRoad(mRoad);
    }

    //POIs:
    //POI search interface:
    String[] poiTags = getResources().getStringArray(R.array.poi_tags);
    poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
            poiTags);
    poiTagText.setAdapter(adapter);
    Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag);
    setPOITagButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Hide the soft keyboard:
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0);
            //Start search:
            getPOIAsync(poiTagText.getText().toString());
        }
    });

    //POI markers:
    final ArrayList<ExtendedOverlayItem> poiItems = new ArrayList<ExtendedOverlayItem>();
    poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, poiItems, map,
            new POIInfoWindow(map));
    map.getOverlays().add(poiMarkers);
    if (savedInstanceState != null) {
        mPOIs = savedInstanceState.getParcelableArrayList("poi");
        updateUIWithPOI(mPOIs);
    }

    // Load friends ListView
    lvListeFriends = (ListView) findViewById(R.id.listViewFriends);
    //lvListeFriends.setBackgroundResource(R.drawable.listview_roundcorner_item);
    lvListeFriends.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            Friends item = (Friends) adapter.getItemAtPosition(position);
            if (item.getLongitude() != 0.0 && item.getLatitude() != 0.0) {
                destinationPoint = new GeoPoint(item.getLongitude(), item.getLatitude());
                markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX,
                        R.string.destination, R.drawable.marker_destination, -1);
                getRoadAsync();
                map.getController().setCenter(destinationPoint);
            } else {
                Toast.makeText(MainActivity.this, R.string.toast_friend_statut, Toast.LENGTH_LONG).show();
            }
        }
    });

    viewMapFilters = (ScrollView) this.findViewById(R.id.scrollViewMapFilters);
    viewMapFilters.setVisibility(View.GONE);

    // Initialiser tout ce qui est donnes utilisateur propres  l'activit
    init();

    getTools().relocateUser(mapController, map, myLocationOverlay, location);
}

From source file:com.mycompany.myfirstindoorsapp.PagedActivity.java

private void checkLocationIsEnabled() {
    // On android Marshmallow we also need to have active Location Services (GPS or Network based)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean isNetworkLocationProviderEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        boolean isGPSLocationProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!isGPSLocationProviderEnabled && !isNetworkLocationProviderEnabled) {
            // Only if both providers are disabled we need to ask the user to do something
            Toast.makeText(this, "Location is off, enable it in system settings.", Toast.LENGTH_LONG).show();
            Intent locationInSettingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            this.startActivityForResult(locationInSettingsIntent, REQUEST_CODE_LOCATION);
        } else {//from w w w.  j a  v a2s  . co m
            continueLoading();
        }
    } else {
        continueLoading();
    }
}