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.swetha.easypark.GetParkingLots.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (!isGooglePlayServicesAvailable()) {
        finish();/* w ww .jav  a 2  s .co m*/
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getparkinglots);

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    googleMap = supportMapFragment.getMap();

    googleMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (gps_enabled) {
        Criteria criteria = new Criteria();

        provider = locationManager.getBestProvider(criteria, true);

        if (provider != null && !provider.equals("")) {

            locationManager.requestLocationUpdates(provider, 500, 1, GetParkingLots.this);
            // Get the location from the given provider 
            location = locationManager.getLastKnownLocation(provider);

        }
    }
    Log.i("GetParkingLots", "Value of network_enabled and location" + network_enabled + location);
    if (location == null && network_enabled) {

        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 1, GetParkingLots.this);

    }

    if (location == null && !network_enabled && !gps_enabled) {
        Toast.makeText(getBaseContext(), "Enable your location services", Toast.LENGTH_LONG).show();
    }
    if (location != null)
        onLocationChanged(location);
    else {

        Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
    }

    tv_fromTime = (TextView) findViewById(R.id.tv_fromTime);
    fromTimeString = Constants.dtf.format(new Date()).toString();
    tv_fromTime.setText(fromTimeString);
    long lval = DateTimeHelpers.convertToLongFromTime(Constants.dtf.format(new Date()).toString());
    Log.i("GetParkingLots",
            "The value of current time:" + Constants.dtf.format(new Date()).toString() + "in long is" + lval);
    Log.i("GetParkingLots",
            "The value of current time:" + lval + "in long is" + DateTimeHelpers.convertToTimeFromLong(lval));
    tv_toTime = (TextView) findViewById(R.id.tv_ToTime);
    // Parsing the date
    toTimeString = Constants.dtf.format(new Date()).toString();
    tv_toTime.setText(toTimeString);

    btnFromTime = (Button) findViewById(R.id.fromButton);
    btnFromTime.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this);
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater()
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
            mDateTimePicker.setDateChangedListener(GetParkingLots.this);

            // Update demo TextViews when the "OK" button is clicked 
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new OnClickListener() {
                        Calendar cal;

                        @SuppressWarnings("deprecation")
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();
                            try {
                                cal = new GregorianCalendar(mDateTimePicker.getYear(),
                                        Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(),
                                        mDateTimePicker.getHour(), mDateTimePicker.getMinute());
                                fromTimeString = DateTimeHelpers.dtf.format(cal.getTime());
                                tv_fromTime.setText(fromTimeString);
                            } catch (Exception e) {
                                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this)
                                        .create();

                                alertDialog.setMessage("Enter a valid date");

                                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                        alertDialog.dismiss();
                                    }
                                });

                                alertDialog.show();
                            }

                            mDateTimeDialog.dismiss();
                        }
                    });

            // Cancel the dialog when the "Cancel" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is clicked

            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();

        }
    });

    btnToTime = (Button) findViewById(R.id.toButton);
    btnToTime.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this);
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater()
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
                    .findViewById(R.id.DateTimePicker);
            mDateTimePicker.setDateChangedListener(GetParkingLots.this);

            // Update demo TextViews when the "OK" button is clicked 
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new OnClickListener() {
                        Calendar cal;

                        @SuppressWarnings("deprecation")
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();

                            Log.i("toButton", "Value of ToString before cal" + toTimeString);
                            try {
                                cal = new GregorianCalendar(mDateTimePicker.getYear(),
                                        Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(),
                                        mDateTimePicker.getHour(), mDateTimePicker.getMinute());
                                toTimeString = DateTimeHelpers.dtf.format(cal.getTime());
                                Log.i("toButton", "Value of ToString before cal" + toTimeString);

                                tv_toTime.setText(toTimeString);

                            } catch (Exception e) // fixing the bug where the user doesnt enter anything in the textbox
                            {
                                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this)
                                        .create();

                                alertDialog.setMessage("Enter a valid date");
                                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        alertDialog.dismiss();
                                    }
                                });

                                alertDialog.show();
                            }
                            //dateTimeTo = new DateTime(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()) ,  mDateTimePicker.getDay(),  mDateTimePicker.getHour(),  mDateTimePicker.getMinute()); ;

                            mDateTimeDialog.dismiss();
                        }
                    });

            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is clicked

            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();

        }
    });

    btnGetParkingLots = (Button) findViewById(R.id.getNearByParkingLotsButton);
    btnGetParkingLots.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            et_search = (EditText) findViewById(R.id.edittextsearch);
            rg = (RadioGroup) findViewById(R.id.rg);
            checkedRbId = rg.getCheckedRadioButtonId();
            Log.i("LOG_TAG: GetParkingLots", "checked radiobutton id is" + checkedRbId);

            if (checkedRbId == R.id.rbradius) {
                isRadiusIndicator = true;
                radius = et_search.getText().toString();
            } else {
                isRadiusIndicator = false;
                zipcode = et_search.getText().toString();
            }

            final Intent intent = new Intent(GetParkingLots.this, DisplayVacantParkingLots.class);
            Log.i(TAG, "Inside getNearByParkingLots");
            Log.i(TAG, "Value of fromString" + fromTimeString);
            long lFromVal = DateTimeHelpers.convertToLongFromTime(fromTimeString);
            Log.i(TAG, "Value of ToString" + toTimeString);
            long lToVal = DateTimeHelpers.convertToLongFromTime(toTimeString);
            if ((lToVal - lFromVal) < Constants.thrityMinInMilliSeconds) {
                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                alertDialog.setMessage("You have to park the car for at least 30 min");

                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        alertDialog.dismiss();
                    }
                });

                alertDialog.show();

            } else {
                intent.putExtra(LATITUDE, latitude);
                intent.putExtra(LONGITUDE, longitude);
                intent.putExtra(FROMTIME, lFromVal);
                intent.putExtra(TOTIME, lToVal);
                intent.putExtra(RadiusOrZIPCODE, isRadiusIndicator);
                if (isRadiusIndicator)
                    try {

                        intent.putExtra(RADIUS, Double.parseDouble(radius));
                        startActivity(intent);
                    } catch (Exception e) {
                        final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                        alertDialog.setMessage("Enter valid radius");

                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                alertDialog.dismiss();

                            }
                        });

                        alertDialog.show();
                    }
                else {
                    try {

                        intent.putExtra(ZIPCODE, Long.parseLong(zipcode));
                        startActivity(intent);
                    } catch (Exception e) {
                        final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                        alertDialog.setMessage("Enter a valid Zip code");

                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                alertDialog.dismiss();

                            }
                        });

                        alertDialog.show();
                    }
                }

            }

        }
    });

}

From source file:com.towson.wavyleaf.Sighting.java

protected void refresh() {
    // Check for GPS
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    playAPKEnabled = doesDeviceHaveGooglePlayServices();

    currentEditableLocation = locationData.getLocation();

    if (!isAccurateLocation(currentEditableLocation)) { // If location isn't accurate

        if (!gpsEnabled) { // If GPS is disabled
            buildAlertMessageNoGps();/*from  w w  w . j  a  v  a2 s  .  c  o m*/
        } else if (gpsEnabled) {
            if (playAPKEnabled) {
                setUpMapIfNeeded();
                wheresWaldo();
            }
        }

        updateLocationTimer = new Timer();
        TimerTask updateLocationTask = new TimerTask() {
            @Override
            public void run() {
                checkLocation();
            }
        };
        updateLocationTimer.scheduleAtFixedRate(updateLocationTask, 0, FIVE_SECONDS);

    } else
        setUpMapIfNeeded();
}

From source file:it.unime.mobility4ckan.MainActivity.java

private boolean isGPSEnable() {
    LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    return mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

From source file:com.waz.zclient.pages.main.conversation.LocationFragment.java

private boolean isLocationServicesEnabled() {
    if (!PermissionUtils.hasSelfPermissions(getContext(), LOCATION_PERMISSIONS)) {
        return false;
    }//from  ww  w. ja  v  a  2  s  . c o  m
    // We are creating a local locationManager here, as it's not sure we already have one
    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);
    if (locationManager == null) {
        return false;
    }
    boolean gpsEnabled;
    boolean netEnabled;

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

    try {
        netEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception e) {
        netEnabled = false;
    }
    return netEnabled || gpsEnabled;
}

From source file:com.snt.bt.recon.activities.MainActivity.java

public boolean gpsStatusCheck() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();//w  w  w . j  a  va2s  . c o  m
        return false;
    } else
        return true;
}

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

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

    LicenseResult licenseResult = ArcGISRuntime.setClientId(CLIENT_ID);
    LicenseLevel licenseLevel = ArcGISRuntime.License.getLicenseLevel();

    if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.BASIC) {
        //Toast.makeText(getApplicationContext(), "Licencia bsica vlida", Toast.LENGTH_SHORT).show();
    } else if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.STANDARD) {
        //Toast.makeText(getApplicationContext(), "Licencia standard vlida", Toast.LENGTH_SHORT).show();
    }// w w w.  j av a  2  s.c o  m

    setContentView(R.layout.activity_reparto);

    Toolbar toolbar = (Toolbar) findViewById(R.id.apptool);
    setSupportActionBar(toolbar);

    myMapView = (MapView) findViewById(R.id.map);
    myMapView.enableWrapAround(true);

    /*Get Credenciales String*/
    Bundle bundle = getIntent().getExtras();
    usuar = bundle.getString("usuario");
    passw = bundle.getString("password");
    modulo = bundle.getString("modulo");
    empresa = bundle.getString("empresa");

    //Crea un intervalo entre primer dia del mes y dia actual
    Calendar oCalendarStart = Calendar.getInstance();
    oCalendarStart.set(Calendar.DAY_OF_MONTH, 1);
    oCalendarStart.set(Calendar.HOUR, 6);

    Calendar oCalendarEnd = Calendar.getInstance();
    oCalendarEnd.set(Calendar.HOUR, 23);

    TimeExtent oTimeInterval = new TimeExtent(oCalendarStart, oCalendarEnd);

    //Set Credenciales
    setCredenciales(usuar, passw);

    if (Build.VERSION.SDK_INT >= 23)
        verifPermisos();
    else
        startGPS();

    setLayersURL(this.getResources().getString(R.string.url_Mapabase), "MAPABASE");
    setLayersURL(this.getResources().getString(R.string.url_token), "TOKENSRV");
    setLayersURL(this.getResources().getString(R.string.srv_Repartos), "SRV_REPARTO");

    LyMapabase = new ArcGISDynamicMapServiceLayer(din_urlMapaBase, null, credenciales);
    LyMapabase.setVisible(true);

    LyReparto = new ArcGISFeatureLayer(srv_reparto, ArcGISFeatureLayer.MODE.ONDEMAND, credenciales);
    LyReparto.setDefinitionExpression(String.format("empresa = '%s'", empresa));
    LyReparto.setTimeInterval(oTimeInterval);
    LyReparto.setMinScale(8000);
    LyReparto.setVisible(true);

    myMapView.addLayer(mRoadBaseMaps, 0);
    myMapView.addLayer(LyReparto, 1);

    sqlReparto = new RepartoSQLiteHelper(RepartoActivity.this, dbName, null, 2);

    txtContador = (TextView) findViewById(R.id.tvContador);
    txtContSesion = (TextView) findViewById(R.id.tvContadorSesion);

    txtListen = (EditText) findViewById(R.id.txtListen);
    txtListen.setEnabled(bGpsActive);
    if (!txtListen.hasFocus())
        txtListen.requestFocus();
    txtListen.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().contains("\n") || s.toString().length() == RepartoClass.length_code) {
                guardarRegistro(s.toString().trim());
                s.clear();
            }
        }
    });

    final FloatingActionButton btnGps = (FloatingActionButton) findViewById(R.id.action_gps);
    btnGps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                myMapView.setExtent(ldm.getPoint());
                myMapView.setScale(4000, true);
            }
        }
    });

    myMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
        @Override
        public void onStatusChanged(Object o, STATUS status) {
            if (ldm != null) {
                Point oPoint = ldm.getPoint();
                myMapView.centerAndZoom(oPoint.getX(), oPoint.getY(), 0.003f);
                myMapView.zoomin(true);
            }

            if (status == STATUS.LAYER_LOADING_FAILED) {
                // Check if a layer is failed to be loaded due to security
                if ((status.getError()) instanceof EsriSecurityException) {
                    EsriSecurityException securityEx = (EsriSecurityException) status.getError();
                    if (securityEx.getCode() == EsriSecurityException.AUTHENTICATION_FAILED)
                        Toast.makeText(myMapView.getContext(),
                                "Su cuenta tiene permisos limitados, contacte con el administrador para solicitar permisos faltantes",
                                Toast.LENGTH_SHORT).show();
                    else if (securityEx.getCode() == EsriSecurityException.TOKEN_INVALID)
                        Toast.makeText(myMapView.getContext(), "Token invlido! Vuelva a iniciar sesin!",
                                Toast.LENGTH_SHORT).show();
                    else if (securityEx.getCode() == EsriSecurityException.TOKEN_SERVICE_NOT_FOUND)
                        Toast.makeText(myMapView.getContext(),
                                "Servicio token no encontrado! Reintente iniciar sesin!", Toast.LENGTH_SHORT)
                                .show();
                    else if (securityEx.getCode() == EsriSecurityException.UNTRUSTED_SERVER_CERTIFICATE)
                        Toast.makeText(myMapView.getContext(), "Untrusted Host! Resubmit!", Toast.LENGTH_SHORT)
                                .show();

                    if (o instanceof ArcGISFeatureLayer) {
                        // Set user credential through username and password
                        UserCredentials creds = new UserCredentials();
                        creds.setUserAccount(usuar, passw);

                        LyMapabase.reinitializeLayer(creds);
                    }
                }
            }
        }
    });

    readCountData();
    updDashboard();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (iContRep > 0) {
                        Toast.makeText(getApplicationContext(), "Sincronizando datos...", Toast.LENGTH_SHORT)
                                .show();
                        readData();
                        enviarDatos();
                    }
                }
            });

        }
    }, 0, 120000);
}

From source file:com.eutectoid.dosomething.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {//  w w  w. jav a  2s  .  c om
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();

            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            // API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            boolean updateLocation = true;
                            Location prevLocation = placePickerFragment.getLocation();
                            if (prevLocation != null) {
                                updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD;
                            }
                            if (updateLocation) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

                        @Override
                        public void onStatusChanged(String s, int i, Bundle bundle) {
                        }

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.taw.gotothere.GoToThereActivity.java

/**
 *  Check if the GPS sensor is switched on.
 *  //from  w w w.  j ava 2  s  . c o m
 *  @return true if on, false otherwise
 */
private boolean isGPSOn() {
    LocationManager locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
    return (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) ? true : false;
}

From source file:com.RSMSA.policeApp.OffenceReportForm.java

/**
 * get the last known location from a specific provider (network/gps)
 *//*  w  w  w  . j a v  a2  s .co m*/
private Location getLocationByProvider(String provider) {
    Location location = null;
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.d(TAG, "Cannot acces Provider " + provider);
    }
    return location;
}

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private void registerLocationListener() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!lm.isProviderEnabled("gps")) {
        new AlertDialog.Builder(this).setMessage(R.string.gps_message).setCancelable(true)
                .setPositiveButton(R.string.enable_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        launchGpsSettings();
                        dialog.dismiss();
                    }/* w  ww  . j  a  v a  2 s  .  co m*/
                }).setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create().show();
    }
    if (lm != null) {
        getBestProvider(lm);
    }
}