Example usage for android.location LocationManager isProviderEnabled

List of usage examples for android.location LocationManager isProviderEnabled

Introduction

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

Prototype

public boolean isProviderEnabled(String provider) 

Source Link

Document

Returns the current enabled/disabled status of the given provider.

Usage

From source file:com.klaasnotfound.locationassistant.LocationAssistant.java

private void checkProviders() {
    // Do it the old fashioned way
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (gps || network)
        return;/*from ww  w .java 2  s  . com*/
    if (listener != null)
        listener.onFallBackToSystemSettings(onGoToLocationSettingsFromView, onGoToLocationSettingsFromDialog);
    else if (!quiet)
        Log.e(getClass().getSimpleName(),
                "Location providers need to be enabled, but no listener is "
                        + "registered! Specify a valid listener when constructing " + getClass().getSimpleName()
                        + " or register it explicitly with register().");
}

From source file:cl.gisred.android.RepartoActivity.java

private boolean verifGPS() {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        alertNoGps();//from  www .  j a v  a  2s. c  om
        return false;
    }
    return true;
}

From source file:org.phillyopen.mytracks.cyclephilly.MainInput.java

/** Called when the activity is first created. */
@Override/* w w  w  .  ja  v a2 s .co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);

    final Firebase ref = new Firebase("https://cyclephilly.firebaseio.com");
    final Firebase phlref = new Firebase("https://phl.firebaseio.com");
    // Let's handle some launcher lifecycle issues:
    // If we're recording or saving right now, jump to the existing activity.
    // (This handles user who hit BACK button while recording)
    setContentView(R.layout.main);
    weatherFont = Typeface.createFromAsset(getAssets(), "cyclephilly.ttf");

    weatherText = (TextView) findViewById(R.id.weatherView);
    weatherText.setTypeface(weatherFont);
    weatherText.setText(R.string.cloudy);

    Intent rService = new Intent(this, RecordingService.class);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            int state = rs.getState();
            if (state > RecordingService.STATE_IDLE) {
                if (state == RecordingService.STATE_FULL) {
                    startActivity(new Intent(MainInput.this, SaveTrip.class));
                } else { // RECORDING OR PAUSED:
                    startActivity(new Intent(MainInput.this, RecordingActivity.class));
                }
                MainInput.this.finish();
            } else {
                // Idle. First run? Switch to user prefs screen if there are no prefs stored yet
                SharedPreferences settings = getSharedPreferences("PREFS", 0);
                String anon = settings.getString("" + PREF_ANONID, "NADA");

                if (settings.getAll().isEmpty()) {
                    showWelcomeDialog();
                } else if (anon == "NADA") {
                    showWelcomeDialog();
                }
                // Not first run - set up the list view of saved trips
                ListView listSavedTrips = (ListView) findViewById(R.id.ListSavedTrips);
                populateList(listSavedTrips);
            }
            MainInput.this.unbindService(this); // race?  this says we no longer care
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    // And set up the record button
    final Button startButton = (Button) findViewById(R.id.ButtonStart);
    final Intent i = new Intent(this, RecordingActivity.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
    SharedPreferences settings = getSharedPreferences("PREFS", 0);
    final String anon = settings.getString("" + PREF_ANONID, "NADA");

    Firebase weatherRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia");
    Firebase tempRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia/currently");

    tempRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Object val = dataSnapshot.getValue();
            String cardinal = null;

            TextView tempState = (TextView) findViewById(R.id.temperatureView);
            //                TextView liveTemp = (TextView) findViewById(R.id.warning);
            String apparentTemp = ((Map) val).get("apparentTemperature").toString();
            String windSpeed = ((Map) val).get("windSpeed").toString();
            Double windValue = (Double) ((Map) val).get("windSpeed");
            Long windBearing = (Long) ((Map) val).get("windBearing");

            //                liveTemp.setText(" "+apparentTemp.toString()+DEGREE);
            WindDirection[] windDirections = WindDirection.values();
            for (int i = 0; i < windDirections.length; i++) {
                if (windDirections[i].startDegree < windBearing && windDirections[i].endDegree > windBearing) {
                    //Get Cardinal direction
                    cardinal = windDirections[i].cardinal;
                }
            }

            if (windValue > 4) {
                tempState.setTextColor(0xFFDC143C);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph. Ride with caution.");
            } else {
                tempState.setTextColor(0xFFFFFFFF);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph.");
            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    connectedListener = ref.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                System.out.println("connected " + dataSnapshot.toString());
                Firebase cycleRef = new Firebase(FIREBASE_REF + "/" + anon + "/connections");
                //                    cycleRef.setValue(Boolean.TRUE);
                //                    cycleRef.onDisconnect().removeValue();
            } else {
                System.out.println("disconnected");
            }
        }

        @Override
        public void onCancelled(FirebaseError error) {
            // No-op
        }
    });
    weatherRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Object value = snapshot.getValue();
            Object hourly = ((Map) value).get("currently");
            String alert = ((Map) hourly).get("summary").toString();
            //                TextView weatherAlert = (TextView) findViewById(R.id.weatherAlert);
            //                weatherAlert.setText(alert);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    // Acquire a reference to the system Location Manager
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            mySpot = new LatLng(location.getLatitude(), location.getLongitude());
            makeUseOfNewLocation(location);
        }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    nearbyStations = (RecyclerView) findViewById(R.id.nearbyStationList);
    nearbyStations.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    //Listener for Indego Changes
    indegoRef = new Firebase("https://phl.firebaseio.com/indego/kiosks");
    indegoRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Updates! Add them to indego data list
            indegoDataList = dataSnapshot;

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    // Register the listener with the Location Manager to receive location updates

    indegoGeofireRef = new Firebase("https://phl.firebaseio.com/indego/_geofire");
    GeoFire geoFire = new GeoFire(indegoGeofireRef);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    mySpot = myCurrentLocation();
    indegoList = new ArrayList<IndegoStation>();
    System.out.println("lo: " + mySpot.toString());

    GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(mySpot.longitude, mySpot.latitude), 0.5);
    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
        @Override
        public void onKeyEntered(String key, GeoLocation location) {
            System.out.println(String.format("Key %s entered the search area at [%f,%f]", key,
                    location.latitude, location.longitude));
            //Create Indego Station object. To-do: check if object exists
            IndegoStation station = new IndegoStation();
            station.kioskId = key;
            station.location = location;
            if (indegoDataList != null) {
                //get latest info from list
                station.name = (String) indegoDataList.child(key).child("properties").child("name").getValue();
            }
            System.out.println(station.name);
            indegoList.add(station);
            //To-do: Add indego station info to RideIndegoAdapter

        }

        @Override
        public void onKeyExited(String key) {

        }

        @Override
        public void onKeyMoved(String key, GeoLocation location) {

        }

        @Override
        public void onGeoQueryReady() {
            System.out.println("GEO READY :" + indegoList.toString());
            indegoAdapter = new RideIndegoAdapter(getApplicationContext(), indegoList);
            nearbyStations.setAdapter(indegoAdapter);

        }

        @Override
        public void onGeoQueryError(FirebaseError error) {
            System.out.println("GEO error");
        }
    });

    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Before we go to record, check GPS status
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
            } else {
                startActivity(i);
                MainInput.this.finish();
            }
        }
    });

    toolbar = (Toolbar) findViewById(R.id.dashboard_bar);
    toolbar.setTitle("Cycle Philly");

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
}

From source file:org.cowboycoders.cyclisimo.turbo.TurboService.java

private void disableLocationProvider(String provider) {
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(provider)) {
        try {//w  w  w  .j a v a2 s  .  c o m
            // is this the same as the below? probably
            locationManager.setTestProviderEnabled(provider, false);
            locationManager.clearTestProviderEnabled(provider);
            locationManager.clearTestProviderLocation(provider);
            locationManager.clearTestProviderStatus(provider);
            locationManager.removeTestProvider(provider);
        } catch (SecurityException e) {
            // ignore 
        }
    }
}

From source file:com.p2p.misc.DeviceUtility.java

public Boolean chkGPS() {
    LocationManager locManager = (LocationManager) mactivity.getSystemService(mactivity.LOCATION_SERVICE);

    Boolean gps = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    System.out.println("IsGPS Present-->>" + gps);
    return gps;//from  w  w  w .j  ava2  s.c  om
}

From source file:org.odk.collect.android.activities.GeoTraceOsmMapActivity.java

private void upMyLocationOverlayLayers() {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        overlayMyLocationLayers();/*from w w  w .j a va  2 s .c o m*/
    } else {
        showGPSDisabledAlertToUser();
    }
}

From source file:org.cowboycoders.cyclisimo.turbo.TurboService.java

private boolean enableLocationProvider(String provider) {
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(provider)) {
        try {//  w w w . j a  v a2  s. c  o  m
            locationManager.addTestProvider(provider, "requiresNetwork" == "", "requiresSatellite" == "",
                    "requiresCell" == "", "hasMonetaryCost" == "", "supportsAltitude" == "",
                    "supportsSpeed" == "", "supportsBearing" == "", android.location.Criteria.POWER_LOW,
                    android.location.Criteria.ACCURACY_FINE);

            locationManager.setTestProviderEnabled(provider, true);
            locationManager.setTestProviderStatus(provider, LocationProvider.AVAILABLE, null,
                    System.currentTimeMillis());
        } catch (SecurityException e) {
            handleException(e, "Error enabling location provider", true, NOTIFCATION_ID_STARTUP);
            return false;
        }
    } else {
        return false;
    }

    return true;
}

From source file:org.odk.collect.android.activities.GeoTraceOsmMapActivity.java

private void disableMyLocation() {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        myLocationOverlay.setEnabled(false);
        myLocationOverlay.disableFollowLocation();
        myLocationOverlay.disableMyLocation();
        gpsStatus = false;/*from w  w w.  j  a v a  2 s.c o m*/
    }

}

From source file:org.opensmc.mytracks.cyclesmc.MainInput.java

/** Called when the activity is first created. */
@Override/*from  ww  w  . j a v a 2s  . co m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);

    final Firebase ref = new Firebase("https://org.opensmc.mytracks.cyclesmc.firebaseio.com");
    final Firebase phlref = new Firebase("https://phl.firebaseio.com");
    // Let's handle some launcher lifecycle issues:
    // If we're recording or saving right now, jump to the existing activity.
    // (This handles user who hit BACK button while recording)
    setContentView(R.layout.main);
    weatherFont = Typeface.createFromAsset(getAssets(), "cyclesmc.ttf");

    weatherText = (TextView) findViewById(R.id.weatherView);
    weatherText.setTypeface(weatherFont);
    weatherText.setText(R.string.cloudy);

    Intent rService = new Intent(this, RecordingService.class);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            int state = rs.getState();
            if (state > RecordingService.STATE_IDLE) {
                if (state == RecordingService.STATE_FULL) {
                    startActivity(new Intent(MainInput.this, SaveTrip.class));
                } else { // RECORDING OR PAUSED:
                    startActivity(new Intent(MainInput.this, RecordingActivity.class));
                }
                MainInput.this.finish();
            } else {
                // Idle. First run? Switch to user prefs screen if there are no prefs stored yet
                SharedPreferences settings = getSharedPreferences("PREFS", 0);
                String anon = settings.getString("" + PREF_ANONID, "NADA");

                if (settings.getAll().isEmpty()) {
                    showWelcomeDialog();
                } else if (anon == "NADA") {
                    showWelcomeDialog();
                }
                // Not first run - set up the list view of saved trips
                ListView listSavedTrips = (ListView) findViewById(R.id.ListSavedTrips);
                populateList(listSavedTrips);
            }
            MainInput.this.unbindService(this); // race?  this says we no longer care
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    // And set up the record button
    final Button startButton = (Button) findViewById(R.id.ButtonStart);
    final Intent i = new Intent(this, RecordingActivity.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
    SharedPreferences settings = getSharedPreferences("PREFS", 0);
    final String anon = settings.getString("" + PREF_ANONID, "NADA");

    Firebase weatherRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia");
    Firebase tempRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia/currently");

    tempRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Object val = dataSnapshot.getValue();
            String cardinal = null;

            TextView tempState = (TextView) findViewById(R.id.temperatureView);
            //                TextView liveTemp = (TextView) findViewById(R.id.warning);
            String apparentTemp = ((Map) val).get("apparentTemperature").toString();
            String windSpeed = ((Map) val).get("windSpeed").toString();
            Double windValue = (Double) ((Map) val).get("windSpeed");
            Long windBearing = (Long) ((Map) val).get("windBearing");

            //                liveTemp.setText(" "+apparentTemp.toString()+DEGREE);
            WindDirection[] windDirections = WindDirection.values();
            for (int i = 0; i < windDirections.length; i++) {
                if (windDirections[i].startDegree < windBearing && windDirections[i].endDegree > windBearing) {
                    //Get Cardinal direction
                    cardinal = windDirections[i].cardinal;
                }
            }

            if (windValue > 4) {
                tempState.setTextColor(0xFFDC143C);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph. Ride with caution.");
            } else {
                tempState.setTextColor(0xFFFFFFFF);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph.");
            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    connectedListener = ref.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                System.out.println("connected " + dataSnapshot.toString());
                //                    Firebase cycleRef = new Firebase(FIREBASE_REF+"/"+anon+"/connections");
                //                    cycleRef.setValue(Boolean.TRUE);
                //                    cycleRef.onDisconnect().removeValue();
            } else {
                System.out.println("disconnected");
            }
        }

        @Override
        public void onCancelled(FirebaseError error) {
            // No-op
        }
    });
    weatherRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Object value = snapshot.getValue();
            Object hourly = ((Map) value).get("currently");
            String alert = ((Map) hourly).get("summary").toString();
            //                TextView weatherAlert = (TextView) findViewById(R.id.weatherAlert);
            //                weatherAlert.setText(alert);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    // Acquire a reference to the system Location Manager
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            mySpot = new LatLng(location.getLatitude(), location.getLongitude());
            makeUseOfNewLocation(location);
        }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    //nearbyStations = (RecyclerView) findViewById(R.id.nearbyStationList);
    //nearbyStations.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    //Listener for Indego Changes
    /*indegoRef = new Firebase("https://phl.firebaseio.com/indego/kiosks");
    indegoRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //Updates! Add them to indego data list
        indegoDataList = dataSnapshot;
            
            
    }
            
    @Override
    public void onCancelled(FirebaseError firebaseError) {
            
    }
    });*/

    // Register the listener with the Location Manager to receive location updates

    //indegoGeofireRef = new Firebase("https://phl.firebaseio.com/indego/_geofire");
    //GeoFire geoFire = new GeoFire(indegoGeofireRef);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    mySpot = myCurrentLocation();
    //indegoList = new ArrayList<IndegoStation>();
    System.out.println("lo: " + mySpot.toString());

    /* GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(mySpot.latitude,mySpot.longitude), 0.5);
     geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
    @Override
    public void onKeyEntered(String key, GeoLocation location) {
        System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude));
        //Create Indego Station object. To-do: check if object exists
       // IndegoStation station = new IndegoStation();
        //station.kioskId = key;
        //station.location = location;
       /* if(indegoDataList != null){
            //get latest info from list
            station.name = (String) indegoDataList.child(key).child("properties").child("name").getValue();
        }
        System.out.println(station.name);
        //indegoList.add(station);
        //To-do: Add indego station info to RideIndegoAdapter
            
    }
            
    @Override
    public void onKeyExited(String key) {
            
    }
            
    @Override
    public void onKeyMoved(String key, GeoLocation location) {
            
    }
            
    @Override
        /* public void onGeoQueryReady() {
        //System.out.println("GEO READY :"+indegoList.toString());
       // indegoAdapter = new RideIndegoAdapter(getApplicationContext(),indegoList);
        //nearbyStations.setAdapter(indegoAdapter);
            
            
    }
            
    @Override
    public void onGeoQueryError(FirebaseError error) {
        System.out.println("GEO error");
    }
     });*/

    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Before we go to record, check GPS status
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
            } else {
                startActivity(i);
                MainInput.this.finish();
            }
        }
    });

    toolbar = (Toolbar) findViewById(R.id.dashboard_bar);
    toolbar.setTitle(getString(R.string.app_name));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
}

From source file:org.cowboycoders.cyclisimo.turbo.TurboService.java

private synchronized void updateLocation(LatLongAlt pos) {
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        try {//ww  w . ja v  a2s .  c om
            float locSpeed = (float) (lastRecordedSpeed / UnitConversions.MS_TO_KMH);
            final long timestamp = System.currentTimeMillis();
            Log.v(TAG, "location timestamp: " + timestamp);
            Location loc = new Location(MOCK_LOCATION_PROVIDER);
            Log.d(TAG, "alt: " + pos.getAltitude());
            Log.d(TAG, "lat: " + pos.getLatitude());
            Log.d(TAG, "long: " + pos.getLongitude());
            loc.setLatitude(pos.getLatitude());
            loc.setLongitude(pos.getLongitude());
            loc.setAltitude(pos.getAltitude());
            loc.setTime(timestamp);
            loc.setSpeed(locSpeed);
            loc.setAccuracy(GPS_ACCURACY);
            locationManager.setTestProviderLocation(MOCK_LOCATION_PROVIDER, loc);
            Log.e(TAG, "updated location");
        } catch (SecurityException e) {
            handleException(e, "Error updating location", true, NOTIFCATION_ID_STARTUP);
        }

        return;
    }
    Log.e(TAG, "no gps provider");

}