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.iride.ayride.HomePageActivity.java

private boolean isGPSEnable() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

}

From source file:com.safecell.HomeScreenActivity.java

public void checkLocationProviderStatus() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        return; // We have GPS do nothing
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        showGPSStatusAlert(LocationManager.NETWORK_PROVIDER);
    } else {//from  ww  w .  j  a va2 s . c  o m
        showGPSStatusAlert(null);
    }
}

From source file:org.akvo.rsr.up.UpdateEditorActivity.java

/**
 * When the user clicks the "Get Location" button, start listening for
 * location updates/*from   w  ww .j  a v a2s. c  o m*/
 */
public void onGetGPSClick(View v) {
    LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (needUpdate) {//turn off
        needUpdate = false;
        btnGpsGeo.setText(R.string.btncaption_gps_position);
        locMgr.removeUpdates(this);
        searchingIndicator.setText("");
        accuracyField.setText("");
        gpsProgress.setVisibility(View.GONE); //hide in-progress wheel
    } else {//turn on
        if (locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            positionGroup.setVisibility(View.VISIBLE);
            accuracyField.setText("?");
            accuracyField.setTextColor(Color.WHITE);
            latField.setText("");
            lonField.setText("");
            eleField.setText("");
            btnGpsGeo.setText(R.string.btncaption_gps_cancel);
            gpsProgress.setVisibility(View.VISIBLE); //Hide progress
            needUpdate = true;
            searchingIndicator.setText(R.string.label_gps_searching);
            lastAccuracy = UNKNOWN_ACCURACY;
            locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        } else {
            // we can't turn GPS on directly, the best we can do is launch the
            // settings page
            DialogUtil.showGPSDialog(this);
        }
    }

}

From source file:com.barkside.travellocblog.LocationUpdates.java

/**
 * Check if user has turned on location services. If not, then we'll never get
 * onConnected or onLocationChanged events.
 * Google Play services does not catch this condition, so have to manually check it.
http://stackoverflow.com/questions/16862987/android-check-location-services-enabled-with-play-services-location-api
 */// ww w .  j  a v a 2 s.c o  m
public boolean isLocationServiceOn() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Was checking for non-empty list locationManager.getProviders(true) but
    // that also contains the PASSIVE provider, which may not return
    // any location in some cases.
    // For best performance, need both GPS and NETWORK, but for this call,
    // will accept either one being on.
    return (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
}

From source file:com.example.angel.parkpanda.MainActivity.java

public Location getLocation() {
    Location location = null;/*from   w  w w .j a v a2s .co m*/
    LocationManager locationManager;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    double longitude, latitude;
    long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
    try {
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

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

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            if (isNetworkEnabled) {
                if (ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(this,
                                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return null;
                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // 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);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

    return location;
}

From source file:com.openatk.fieldnotebook.MainActivity.java

private void checkGPS() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();//from  www  .j av  a2 s .c  o m
    }
}

From source file:plugin.google.maps.CordovaGoogleMaps.java

private void _onActivityResultLocationPage(Bundle bundle) {
    String callbackId = bundle.getString("callbackId");
    CallbackContext callbackContext = new CallbackContext(callbackId, this.webView);

    LocationManager locationManager = (LocationManager) this.activity
            .getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    int availableProviders = 0;
    if (mPluginLayout != null && mPluginLayout.isDebug) {
        Log.d(TAG, "---debug at getMyLocation(available providers)--");
    }/* w  ww . j a va2s. c  om*/
    Iterator<String> iterator = providers.iterator();
    String provider;
    boolean isAvailable;
    while (iterator.hasNext()) {
        provider = iterator.next();
        isAvailable = locationManager.isProviderEnabled(provider);
        if (isAvailable) {
            availableProviders++;
        }
        if (mPluginLayout != null && mPluginLayout.isDebug) {
            Log.d(TAG, "   " + provider + " = " + (isAvailable ? "" : "not ") + "available");
        }
    }
    if (availableProviders == 0) {
        JSONObject result = new JSONObject();
        try {
            result.put("status", false);
            result.put("error_code", "not_available");
            result.put("error_message",
                    "Since this device does not have any location provider, this app can not detect your location.");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        callbackContext.error(result);
        return;
    }

    _inviteLocationUpdateAfterActivityResult(bundle);
}

From source file:edu.princeton.jrpalmer.asmlibrary.Settings.java

@Override
protected void onResume() {

    if (Util.trafficCop(this))
        finish();//from  w  ww .ja  v  a2  s  .  co m
    IntentFilter uploadFilter;
    uploadFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_UPLOADED);
    uploadReceiver = new UploadReceiver();
    registerReceiver(uploadReceiver, uploadFilter);

    IntentFilter fixFilter;
    fixFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_RECORDED);
    fixReceiver = new FixReceiver();
    registerReceiver(fixReceiver, fixFilter);

    shareMyData = PropertyHolder.getShareData();

    toggleParticipationViews(shareMyData);

    int nUploads = PropertyHolder.getNUploads();

    final long participationTime = PropertyHolder.ptCheck();
    participationTimeText.setBase(SystemClock.elapsedRealtime() - participationTime);

    // service button
    boolean isServiceOn = PropertyHolder.isServiceOn();

    mServiceButton.setChecked(isServiceOn);
    mServiceButton.setOnClickListener(new ToggleButton.OnClickListener() {
        public void onClick(View view) {
            if (view.getId() != R.id.service_button)
                return;
            Context context = view.getContext();
            boolean on = ((ToggleButton) view).isChecked();
            String schedule = on ? Util.MESSAGE_SCHEDULE : Util.MESSAGE_UNSCHEDULE;
            // Log.e(TAG, schedule + on);

            // now schedule or unschedule
            Intent intent = new Intent(getString(R.string.internal_message_id) + schedule);
            context.sendBroadcast(intent);
            showSpinner(on, storeMyData);

            if (on && shareMyData) {
                final long ptNow = PropertyHolder.ptStart();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.start();

                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                        "on," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));
            } else {

                final long ptNow = PropertyHolder.ptStop();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.stop();
                // stop uploader
                Intent stopUploaderIntent = new Intent(Settings.this, FileUploader.class);
                // Stop service if it is currently running
                stopService(stopUploaderIntent);

                if (shareMyData) {

                    ContentResolver ucr = getContentResolver();

                    ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                            "off," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));

                }

            }
            // If user turns CountdownDisplay on but GPS is not on, remind
            // user to turn
            // GPS on
            if (on) {
                final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                        buildAlertMessageNoGpsNoNet();
                    } else
                        buildAlertMessageNoGps();
                }
            }

            return;
        }
    });

    // interval spinner
    int intspinner_item = android.R.layout.simple_spinner_item;
    int dropdown_item = android.R.layout.simple_spinner_dropdown_item;
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.interval_array,
            intspinner_item);
    adapter.setDropDownViewResource(dropdown_item);
    mIntervalSpinner.setAdapter(adapter);
    mIntervalSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_interval)
                return;
            if (pos > mInterval.length)
                return;
            if (!PropertyHolder.isServiceOn()) {
                PropertyHolder.setAlarmInterval(mInterval[pos]);
                return;
            }
            PropertyHolder.setAlarmInterval(mInterval[pos]);
            mServiceButton.setChecked(true);

            Intent intent = new Intent(getString(R.string.internal_message_id) + Util.MESSAGE_SCHEDULE);
            Context context = getApplicationContext();
            context.sendBroadcast(intent);
            showSpinner(true, storeMyData);

            if (shareMyData) {
                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("INT",
                        Util.iso8601(System.currentTimeMillis()) + "," + mInterval[pos]));
            }
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int pos = ai2pos(PropertyHolder.getAlarmInterval());
    mIntervalSpinner.setSelection(pos);
    showSpinner(isServiceOn, storeMyData);

    // mydata buttons

    // storage spinner

    storageDays = PropertyHolder.getStorageDays();

    mStorageSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_mydata)
                return;
            if (pos > MAX_STORAGE - MIN_STORAGE)
                return;
            PropertyHolder.setStorageDays(pos + MIN_STORAGE);
            PropertyHolder.setStoreMyData((pos + MIN_STORAGE) > 0);
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int storagepos = storageDays - MIN_STORAGE;
    mStorageSpinner.setSelection(storagepos);

    // NEW STUFF
    mToggleSatRadioGroup = (RadioGroup) findViewById(R.id.toggleSatRadioGroup);
    mToggleIconsRadioGroup = (RadioGroup) findViewById(R.id.toggleIconsRadioGroup);
    mToggleAccRadioGroup = (RadioGroup) findViewById(R.id.toggleAccRadioGroup);
    mLimitStartDateRadioGroup = (RadioGroup) findViewById(R.id.limitStartDateRadioGroup);
    mLimitEndDateRadioGroup = (RadioGroup) findViewById(R.id.limitEndDateRadioGroup);

    Intent i = getIntent();
    if (i.getBooleanExtra(MapMyData.DATES_BUTTON_MESSAGE, false)) {

        RelativeLayout dateSettingsArea = (RelativeLayout) findViewById(R.id.dateSettingsArea);
        dateSettingsArea.setFocusable(true);
        dateSettingsArea.setFocusableInTouchMode(true);
        dateSettingsArea.requestFocus();
    }

    if (shareMyData && isServiceOn) {
        participationTimeText.setBase(SystemClock.elapsedRealtime() - PropertyHolder.ptStart());
        participationTimeText.start();
    }

    nUploadsText.setText(String.valueOf(nUploads));

    if (nUploads >= Util.UPLOADS_TO_PRO && !PropertyHolder.getProVersion()
            && participationTime >= Util.TIME_TO_PRO) {
        Util.createProNotification(context);
        PropertyHolder.setProVersion(true);
        PropertyHolder.setNeedsDebriefingSurvey(true);
    }

    boolean proV = PropertyHolder.getProVersion();

    // 19 December 2013: end of research changes
    mShareDataRadioGroup.check(R.id.sharedataNo);

    mShareDataRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.sharedataYes) {
                buildSharingOverAnnouncement();
            }
            mShareDataRadioGroup.check(R.id.sharedataNo);
        }
    });

    /*
     * if (proV) {
     * 
     * if (shareMyData) { mShareDataRadioGroup.check(R.id.sharedataYes); if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context); } }
     * else { mShareDataRadioGroup.check(R.id.sharedataNo); }
     * 
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { shareMyData = (checkedId == R.id.sharedataYes);
     * PropertyHolder.setShareData(shareMyData);
     * toggleParticipationViews(shareMyData); final boolean on =
     * PropertyHolder.isServiceOn(); if (shareMyData) { if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context);
     * 
     * } if (on) {
     * 
     * final long ptNow = PropertyHolder.ptStart();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow);
     * 
     * participationTimeText.start();
     * 
     * ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "on," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * } } else {
     * 
     * final long ptNow = PropertyHolder.ptStop();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow); participationTimeText.stop(); // stop uploader Intent i = new
     * Intent(Settings.this, FileUploader.class); // Stop service if it is
     * currently running stopService(i);
     * 
     * if (on) { ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "off," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * }
     * 
     * }
     * 
     * } }); } else { mShareDataRadioGroup.check(R.id.sharedataYes);
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { if (checkedId == R.id.sharedataNo) {
     * mShareDataRadioGroup.check(R.id.sharedataYes);
     * showCurrentlySharingDialog(); } } });
     * 
     * }
     */
    new CheckPendingUploadsSizeTask().execute(context);
    new CheckUserDbSizeTask().execute(context);

    deletePendingUploadsButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getUploadQueueUri(context), "1", null);

            // Log.i("Settings", "number of rows deleted=" + nDeleted);
            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");

            updateStorageSizes();

        }

    });

    deleteUserDbButton = (ImageButton) findViewById(R.id.deleteMyDbButton);

    deleteUserDbButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getFixesUri(context), "1", null);

            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");
            updateStorageSizes();

        }

    });

    uploadButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (Util.isOnline(context)) {
                Intent i = new Intent(Settings.this, FileUploader.class);
                startService(i);

                new UploadMessageTask().execute(context);
            } else {
                Util.toast(context, getResources().getString(R.string.offline_warning));
            }

        }

    });

    mToggleSatRadioGroup.check(PropertyHolder.getMapSat() ? R.id.toggleSatYes : R.id.toggleSatNo);

    mToggleSatRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapSat(checkedId == R.id.toggleSatYes);
        }
    });

    mToggleIconsRadioGroup.check(PropertyHolder.getMapIcons() ? R.id.toggleIconsYes : R.id.toggleIconsNo);

    mToggleIconsRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapIcons(checkedId == R.id.toggleIconsYes);
        }
    });

    mToggleAccRadioGroup.check(PropertyHolder.getMapAcc() ? R.id.toggleAccYes : R.id.toggleAccNo);

    mToggleAccRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapAcc(checkedId == R.id.toggleAccYes);
        }
    });

    mStartDateButton = (Button) findViewById(R.id.startDateButton);
    mEndDateButton = (Button) findViewById(R.id.endDateButton);

    boolean limitStartDate = PropertyHolder.getLimitStartDate();
    boolean limitEndDate = PropertyHolder.getLimitEndDate();

    if (!limitStartDate)
        mStartDateButton.setVisibility(View.GONE);
    else {
        mStartDateButton.setVisibility(View.VISIBLE);

    }
    if (!limitEndDate)
        mEndDateButton.setVisibility(View.GONE);
    else {
        mEndDateButton.setVisibility(View.VISIBLE);
    }

    mLimitStartDateRadioGroup.check(limitStartDate ? R.id.limitStartDateYes : R.id.limitStartDateNo);

    mLimitStartDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitStartDate(checkedId == R.id.limitStartDateYes);

            if (checkedId != R.id.limitStartDateYes)
                mStartDateButton.setVisibility(View.GONE);
            else {
                mStartDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mLimitEndDateRadioGroup.check(limitEndDate ? R.id.limitEndDateYes : R.id.limitEndDateNo);

    mLimitEndDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitEndDate(checkedId == R.id.limitEndDateYes);

            if (checkedId != R.id.limitEndDateYes)
                mEndDateButton.setVisibility(View.GONE);
            else {
                mEndDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mStartDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapStartDate()));
    mStartDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new StartDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    mEndDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapEndDate()));
    mEndDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new EndDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    if (PropertyHolder.getNeedsDebriefingSurvey()) {
        buildProAnnouncement();
        PropertyHolder.setNeedsDebriefingSurvey(false);
    }

    super.onResume();

}

From source file:com.example.demo_dv_fuse.MapScreen.java

/**
 * @see android.app.Activity#onCreate(android.os.Bundle)
 *///from ww w .j av  a 2 s.  c  om
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_screen);
    this.map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapView)).getMap();
    this.map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    if (status == ConnectionResult.SUCCESS) { // Google Play Services is available
        // Enabling MyLocation Layer of Google Map
        this.map.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        final Criteria criteria = new Criteria();

        // Getting the name of the best provider
        final String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        final Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
            //            } else {
            //                final String coordinates[] = {"1.352566007", "103.78921587"};
            //                final double lat = Double.parseDouble(coordinates[0]);
            //                final double lng = Double.parseDouble(coordinates[1]);
            //
            //                // Creating a LatLng object for the current location
            //                LatLng latLng = new LatLng(lat, lng);
            //
            //                // Showing the current location in Google Map
            //                this.map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            //                this.map.animateCamera(CameraUpdateFactory.zoomTo(15));
        }
        boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        // Check if enabled and if not send user to the GSP settings
        // Better solution would be to display a dialog and suggesting to 
        // go to the settings
        if (!enabledGPS || !enabledWiFi) {
            Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
    } else { // Google Play Services are not available
        final int requestCode = 10;
        final Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();
    }
}

From source file:net.movelab.cmlibrary.MapMyData.java

@Override
protected void onResume() {

    Context context = getApplicationContext();

    Log.e("TAPMAP", "selectPZ=" + selectNewPrivacyZone);

    if (Util.trafficCop(this))
        finish();//www.j a v  a 2 s.  co m
    dateRangeText.setBackgroundResource(R.drawable.red_border);

    if (reloadData) {
        mPoints.clear();
        lastRecId = 0;
    }

    isServiceOn = PropertyHolder.isServiceOn();
    shareData = PropertyHolder.getShareData();
    drawConfidenceCircles = PropertyHolder.getMapAcc();
    drawIcons = PropertyHolder.getMapIcons();
    satToggle = PropertyHolder.getMapSat();
    mapView.setSatellite(satToggle);

    if (PropertyHolder.getLimitEndDate())
        dateRangeText.setText(Util.userDate(PropertyHolder.getMapStartDate()) + " - "
                + Util.userDate(PropertyHolder.getMapEndDate()));
    else
        dateRangeText.setText(Util.userDate(PropertyHolder.getMapStartDate()) + " - "
                + getResources().getString(R.string.present));

    if (Util.needDatabaseUpdate) {

        progressbarText.setText(getResources().getString(R.string.database_updating_text));

        if (updatingDatabase == false) {
            updatingDatabase = true;
            new DatabaseUpdateTask().execute(context);
        }
    } else {
        progressNotificationArea.setVisibility(View.VISIBLE);
        progressbarText.setText(getResources().getString(R.string.mapdata_loading_text));

        if (loadingData == false) {
            loadingData = true;
            new DataGrabberTask().execute(context);
        }

    }

    receiverNotificationArea.setVisibility(View.INVISIBLE);

    if (isServiceOn) {
        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                receiverNotificationArea.setVisibility(View.VISIBLE);

                mReceiversOffWarning.setText(getResources().getString(R.string.noGPSnoNet));
            } else {
                receiverNotificationArea.setVisibility(View.VISIBLE);

                mReceiversOffWarning.setText(getResources().getString(R.string.noGPS));
            }

            mReceiversOffWarning.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

                }
            });

        }

    } else {

        receiverNotificationArea.setVisibility(View.VISIBLE);

        mReceiversOffWarning.setText(getResources().getString(R.string.main_text_off));

        mReceiversOffWarning.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent e) {

                if (e.getAction() == MotionEvent.ACTION_DOWN) {
                    receiverNotificationArea
                            .setBackgroundColor(getResources().getColor(R.color.push_button_color));
                }
                if (e.getAction() == MotionEvent.ACTION_UP) {
                    receiverNotificationArea.setBackgroundColor(getResources().getColor(R.color.dark_grey));
                }

                return false;
            }

        });

        mReceiversOffWarning.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getString(R.string.internal_message_id) + Util.MESSAGE_SCHEDULE);
                sendBroadcast(intent);
                receiverNotificationArea.setVisibility(View.INVISIBLE);

            }
        });

    }

    IntentFilter fixFilter;
    fixFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_RECORDED);
    fixReceiver = new FixReceiver();
    registerReceiver(fixReceiver, fixFilter);

    super.onResume();

}