Example usage for android.content Context LOCATION_SERVICE

List of usage examples for android.content Context LOCATION_SERVICE

Introduction

In this page you can find the example usage for android.content Context LOCATION_SERVICE.

Prototype

String LOCATION_SERVICE

To view the source code for android.content Context LOCATION_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.location.LocationManager for controlling location updates.

Usage

From source file:com.crearo.gpslogger.GpsLoggingService.java

/**
 * Starts the location manager. There are two location managers - GPS and
 * Cell Tower. This code determines which manager to request updates from
 * based on user preference and whichever is enabled. If GPS is enabled on
 * the phone, that is used. But if the user has also specified that they
 * prefer cell towers, then cell towers are used. If neither is enabled,
 * then nothing is requested.//from  w  ww . j a v a2 s. c  om
 */
private void startGpsManager() {

    //If the user has been still for more than the minimum seconds
    if (userHasBeenStillForTooLong()) {
        LOG.info("No movement detected in the past interval, will not log");
        setAlarmForNextPoint();
        return;
    }

    if (gpsLocationListener == null) {
        gpsLocationListener = new GeneralLocationListener(this, "GPS");
    }

    if (towerLocationListener == null) {
        towerLocationListener = new GeneralLocationListener(this, "CELL");
    }

    gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    towerLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    checkTowerAndGpsStatus();

    if (Session.isGpsEnabled()
            && preferenceHelper.getChosenListeners().contains(LocationManager.GPS_PROVIDER)) {
        LOG.info("Requesting GPS location updates");
        // gps satellite based
        gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, gpsLocationListener);
        gpsLocationManager.addGpsStatusListener(gpsLocationListener);
        gpsLocationManager.addNmeaListener(gpsLocationListener);

        Session.setUsingGps(true);
        startAbsoluteTimer();
    }

    if (Session.isTowerEnabled()
            && (preferenceHelper.getChosenListeners().contains(LocationManager.NETWORK_PROVIDER)
                    || !Session.isGpsEnabled())) {
        LOG.info("Requesting cell and wifi location updates");
        Session.setUsingGps(false);
        // Cell tower and wifi based
        towerLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
                towerLocationListener);

        startAbsoluteTimer();
    }

    if (!Session.isTowerEnabled() && !Session.isGpsEnabled()) {
        LOG.error("No provider available!");
        Session.setUsingGps(false);
        LOG.error(getString(R.string.gpsprovider_unavailable));
        stopLogging();
        setLocationServiceUnavailable();
        return;
    }

    EventBus.getDefault().post(new ServiceEvents.WaitingForLocation(true));
    Session.setWaitingForLocation(true);
}

From source file:in.codehex.arrow.MainActivity.java

/**
 * @param context context of the MainActivity class
 * @return true if GPS is enabled else false
 *//*from w w  w . j  a v  a 2 s . c  om*/
private boolean isGPSEnabled(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

From source file:com.mjhram.geodata.GpsLoggingService.java

/**
 * Starts the location manager. There are two location managers - GPS and
 * Cell Tower. This code determines which manager to request updates from
 * based on user preference and whichever is enabled. If GPS is enabled on
 * the phone, that is used. But if the user has also specified that they
 * prefer cell towers, then cell towers are used. If neither is enabled,
 * then nothing is requested.//from   ww  w .  j av  a  2s . com
 */
private void StartGpsManager() {

    //If the user has been still for more than the minimum seconds
    if (userHasBeenStillForTooLong()) {
        tracer.info("No movement detected in the past interval, will not log");
        SetAlarmForNextPoint();
        return;
    }

    if (gpsLocationListener == null) {
        gpsLocationListener = new GeneralLocationListener(this, "GPS");
    }

    if (towerLocationListener == null) {
        towerLocationListener = new GeneralLocationListener(this, "CELL");
    }

    gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    towerLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    CheckTowerAndGpsStatus();

    if (Session.isGpsEnabled() && AppSettings.getChosenListeners().contains("gps")) {
        tracer.info("Requesting GPS location updates");
        // gps satellite based
        gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, gpsLocationListener);
        gpsLocationManager.addGpsStatusListener(gpsLocationListener);
        //gpsLocationManager.addNmeaListener(gpsLocationListener);

        Session.setUsingGps(true);
        startAbsoluteTimer();
    }

    if (Session.isTowerEnabled()
            && (AppSettings.getChosenListeners().contains("network") || !Session.isGpsEnabled())) {
        tracer.info("Requesting cell and wifi location updates");
        Session.setUsingGps(false);
        // Cell tower and wifi based
        towerLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
                towerLocationListener);

        startAbsoluteTimer();
    }

    if (!Session.isTowerEnabled() && !Session.isGpsEnabled()) {
        tracer.error("No provider available!");
        Session.setUsingGps(false);
        tracer.error(getString(R.string.gpsprovider_unavailable));
        //StopLogging();
        SetLocationServiceUnavailable();
        return;
    }

    EventBus.getDefault().post(new ServiceEvents.WaitingForLocation(true));
    Session.setWaitingForLocation(true);
}

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  w w  w.j  av  a2 s .  c o  m
    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:com.raddapp.radika.raddappv001.GpsLoggingService.java

/**
 * Starts the location manager. There are two location managers - GPS and
 * Cell Tower. This code determines which manager to request updates from
 * based on user preference and whichever is enabled. If GPS is enabled on
 * the phone, that is used. But if the user has also specified that they
 * prefer cell towers, then cell towers are used. If neither is enabled,
 * then nothing is requested./*ww  w .  j  ava2s .  c o m*/
 */
private void StartGpsManager() {
    Log.d("GPSLOGSERV 101", "StartGpsManager");
    //If the user has been still for more than the minimum seconds
    if (userHasBeenStillForTooLong()) {
        //tracer.info("No movement detected in the past interval, will not log");
        SetAlarmForNextPoint();
        return;
    }

    if (gpsLocationListener == null) {
        gpsLocationListener = new GeneralLocationListener(this, "GPS");
    }

    if (towerLocationListener == null) {
        towerLocationListener = new GeneralLocationListener(this, "CELL");
    }

    gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    towerLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    CheckTowerAndGpsStatus();

    if (Session.isGpsEnabled()) { // && AppSettings.getChosenListeners().contains("gps")
        //tracer.info("Requesting GPS location updates");
        // gps satellite based

        gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, gpsLocationListener);
        gpsLocationManager.addGpsStatusListener(gpsLocationListener);
        // gpsLocationManager.addNmeaListener(gpsLocationListener);

        Session.setUsingGps(true);
        startAbsoluteTimer();
    }

    /*if (Session.isTowerEnabled() &&  ( AppSettings.getChosenListeners().contains("network")  || !Session.isGpsEnabled() ) ) {
    tracer.info("Requesting cell and wifi location updates");
    Session.setUsingGps(false);
    // Cell tower and wifi based
    towerLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, towerLocationListener);
            
    startAbsoluteTimer();
    }*/

    if (!Session.isTowerEnabled() && !Session.isGpsEnabled()) {
        //tracer.error("No provider available!");
        Session.setUsingGps(false);
        //tracer.error("GPS unavaiable");//getString(R.string.gpsprovider_unavailable)
        StopLogging();
        SetLocationServiceUnavailable();
        return;
    }

    //EventBus.getDefault().post(new ServiceEvents.WaitingForLocation(true));
    Session.setWaitingForLocation(true);
}

From source file:com.moodmap.HomeActivity.java

private void registerLocationListeners() {
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (mLocationListener_Fine == null) {
        mLocationListener_Fine = new LocationListener() {
            // LocationListener
            @Override// w w  w  .j  ava 2  s  . c  om
            public void onLocationChanged(Location location) {

                float currentLocationAccuracy = location.getAccuracy();

                myLocationFixCnt_Fine++;
                if ((myLocationFixCnt_Fine >= Constants.kMaxGpsFixCnt)
                        || ((location.hasAccuracy()) && (currentLocationAccuracy <= 60.0))) // tighter,
                                                                                                                                                   // slower
                                                                                                                                                   // location
                {
                    // stop the fine location service
                    mLocationManager.removeUpdates(this);

                    // also stop the coarse location updates, if for some
                    // reason it has not resolved yet
                    if (mLocationListener_Coarse != null) {
                        mLocationManager.removeUpdates(mLocationListener_Coarse);
                    }
                }
                updateMyLocation(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.v(Constants.LOGTAG, "Fine Provider Disabled: " + provider);
            }

            @Override
            public void onProviderEnabled(String provider) {
                Log.v(Constants.LOGTAG, "Fine Provider Enabled: " + provider);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                myStatusChangeCnt_Fine++;
                if ((status == LocationProvider.OUT_OF_SERVICE))
                // not sure if needed (myStatusChangeCnt_Fine >=
                // Constants.kMaxGpsFixCnt))
                {
                    // if cannot resolve the location, do not leave the gps
                    // running
                    mLocationManager.removeUpdates(mLocationListener_Fine);
                }
                Log.v(Constants.LOGTAG, "Fine Provider Status Change (OVER): " + provider + " status:" + status
                        + " myStatusChangeCnt_Fine:" + myStatusChangeCnt_Fine);

                // LocationProvider.OUT_OF_SERVICE
            }
        };
    }

    if (mLocationListener_Coarse == null) {
        mLocationListener_Coarse = new LocationListener() {
            // LocationListener
            @Override
            public void onLocationChanged(Location location) {

                float currentLocationAccuracy = location.getAccuracy();

                myLocationFixCnt_Coarse++;
                if ((myLocationFixCnt_Coarse >= Constants.kMaxGpsFixCnt)
                        || ((location.hasAccuracy()) && (currentLocationAccuracy <= 1000.0))) // quick,
                                                                                                                                                       // rough
                                                                                                                                                       // location
                {
                    // stop the coarse location service
                    mLocationManager.removeUpdates(this);
                }
                updateMyLocation(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.v(Constants.LOGTAG, "Provider Disabled: " + provider);
            }

            @Override
            public void onProviderEnabled(String provider) {
                Log.v(Constants.LOGTAG, "Provider Enabled: " + provider);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.v(Constants.LOGTAG, "Provider Status Change: " + provider + " status:" + status);
                // LocationProvider.OUT_OF_SERVICE
            }
        };
    }

    // still in registerLocationListeners
    //
    String provider = null;
    Criteria crta = new Criteria();
    crta.setAccuracy(Criteria.ACCURACY_FINE);
    crta.setAltitudeRequired(false);
    crta.setBearingRequired(false);
    crta.setCostAllowed(false); // Indicates whether the provider is allowed
                                // to incur monetary cost.
                                // crta.setPowerRequirement(Criteria.POWER_MEDIUM); // POWER_LOW);
    provider = mLocationManager.getBestProvider(crta, true);
    // provider = LocationManager.NETWORK_PROVIDER;

    // get the last, possibly very wrong location
    currentLocation = mLocationManager.getLastKnownLocation(provider);
    // updateMyLocation(location);

    // minTime (2nd) the minimum time interval for notifications, in
    // milliseconds. This field is only used as a hint to conserve power,
    // and actual time between location updates may be greater or lesser
    // than this value.
    // minDistance (3rd)the minimum distance interval for notifications, in
    // meters
    // should be ~ 10000, 100
    // mLocationManager.requestLocationUpdates(provider, 3000, 50,
    // mLocationListener_Fine);
    mLocationManager.requestLocationUpdates(provider, 3000, 0, mLocationListener_Fine);

    // Add second quick location provider
    Criteria coarse = new Criteria();
    coarse.setAccuracy(Criteria.ACCURACY_COARSE);
    coarse.setAltitudeRequired(false);
    coarse.setBearingRequired(false);
    // coarse.setCostAllowed(false);
    // crta.setPowerRequirement(Criteria.POWER_MEDIUM); // POWER_LOW);
    String coarseProvider = mLocationManager.getBestProvider(coarse, true);
    if ((provider != null) && (!provider.contentEquals(coarseProvider))) {
        // only add coarse location resolution if DIFFERENT than the fine
        // location provider
        mLocationManager.requestLocationUpdates(coarseProvider, 1000, 1000, mLocationListener_Coarse);
    }
}

From source file:com.wbtech.ums.UmsAgent.java

private static JSONObject getClientDataJSONObject(Context context) {
    TelephonyManager tm = (TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE));
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics displaysMetrics = new DisplayMetrics();
    manager.getDefaultDisplay().getMetrics(displaysMetrics);
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    JSONObject clientData = new JSONObject();
    try {/*from w  w w .  j  av a2s. c o m*/
        clientData.put("os_version", CommonUtil.getOsVersion(context));
        clientData.put("platform", "android");
        clientData.put("language", Locale.getDefault().getLanguage());
        clientData.put("deviceid", tm.getDeviceId() == null ? "" : tm.getDeviceId());//
        clientData.put("appkey", CommonUtil.getAppKey(context));
        clientData.put("resolution", displaysMetrics.widthPixels + "x" + displaysMetrics.heightPixels);
        clientData.put("ismobiledevice", true);
        clientData.put("phonetype", tm.getPhoneType());//
        clientData.put("imsi", tm.getSubscriberId());
        clientData.put("network", CommonUtil.getNetworkTypeWIFI2G3G(context));
        clientData.put("time", CommonUtil.getTime());
        clientData.put("version", CommonUtil.getVersion(context));
        clientData.put(UserIdentifier, CommonUtil.getUserIdentifier(context));

        SCell sCell = CommonUtil.getCellInfo(context);

        clientData.put("mccmnc", sCell != null ? "" + sCell.MCCMNC : "");
        clientData.put("cellid", sCell != null ? sCell.CID + "" : "");
        clientData.put("lac", sCell != null ? sCell.LAC + "" : "");
        clientData.put("modulename", Build.PRODUCT);
        clientData.put("devicename", CommonUtil.getDeviceName());
        clientData.put("wifimac", wifiManager.getConnectionInfo().getMacAddress());
        clientData.put("havebt", adapter == null ? false : true);
        clientData.put("havewifi", CommonUtil.isWiFiActive(context));
        clientData.put("havegps", locationManager == null ? false : true);
        clientData.put("havegravity", CommonUtil.isHaveGravity(context));//

        LatitudeAndLongitude coordinates = CommonUtil.getLatitudeAndLongitude(context,
                UmsAgent.mUseLocationService);
        clientData.put("latitude", coordinates.latitude);
        clientData.put("longitude", coordinates.longitude);
        CommonUtil.printLog("clientData---------->", clientData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return clientData;
}

From source file:gov.nasa.arc.geocam.geocam.GeoCamService.java

@Override
public void onCreate() {
    Log.d(GeoCamMobile.DEBUG_ID, "GeoCamService::onCreate called");
    super.onCreate();

    // Prevent this service from being prematurely killed to reclaim memory
    buildNotification("GeoCam uploader starting...", "Starting...");
    Reflect.Service.startForeground(this, NOTIFICATION_ID, mNotification);

    // Location Manager
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    registerListener();//from   w w  w . j a  va2  s .  co m

    mLocationManager.addGpsStatusListener(mGpsStatusListener);

    // Notification Manager
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Upload queue and thread
    // Initialize with mCv open so we immediately try to upload when the thread is spawned
    // This is important on service restart with non-zero length queue
    // The thread will close mCv if the queue is empty
    mCv = new ConditionVariable(true);
    mIsUploading = new AtomicBoolean(false);
    mLastStatus = new AtomicInteger(0);

    if (mUploadQueue == null) {
        mUploadQueue = new GeoCamDbAdapter(this);
        mUploadQueue.open();
    }

    if (mGpsLog == null) {
        mGpsLog = new GpsDbAdapter(this);
        mGpsLog.open();
    }

    mPrefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            // wake up upload thread if upload was just enabled
            boolean isUploadEnabled = prefs.getBoolean(GeoCamMobile.SETTINGS_SERVER_UPLOAD_ENABLED, true);
            Log.d(GeoCamMobile.DEBUG_ID, "GeoCamService.mPrefListener.onSharedPreferenceChanged" + " key=" + key
                    + " isUploadEnabled=" + Boolean.toString(isUploadEnabled));
            if (key.equals(GeoCamMobile.SETTINGS_SERVER_UPLOAD_ENABLED) && isUploadEnabled) {
                Log.d(GeoCamMobile.DEBUG_ID,
                        "GeoCamService.mPrefListener.onSharedPreferenceChanged" + " waking up upload thread");
                mCv.open();
            }
        }
    };
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    settings.registerOnSharedPreferenceChangeListener(mPrefListener);

    mUploadThread = new Thread(null, uploadTask, "UploadThread");
    mUploadThread.start();
}

From source file:com.trailbehind.android.iburn.map.MapActivity.java

/**
 * Check gps provider.//from   ww  w.ja v  a2s  .c om
 */
private void checkGPSProvider() {
    final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        mProgressBar.setVisibility(View.GONE);
        mMessageTextView.setText(R.string.error_gps_disabled);
        mMessageTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mVibrator.vibrate(50);

                    final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                } catch (Exception e) {
                    // we dont care
                }
            }
        });

        UIUtils.showPanel(getBaseContext(), mMessagePanel, false);
    } else if (Globals.sCurrentGPSLocation == null) {
        mProgressBar.setVisibility(View.VISIBLE);
        mMessageTextView.setText(R.string.msg_locating);

        UIUtils.showPanel(getBaseContext(), mMessagePanel, false);
    } else {
        UIUtils.hidePanel(getBaseContext(), mMessagePanel, false);
    }
}

From source file:xj.property.ums.UmsAgent.java

public static JSONObject getClientDataJSONObject(Context context) {
    TelephonyManager tm = (TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE));
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics displaysMetrics = new DisplayMetrics();
    manager.getDefaultDisplay().getMetrics(displaysMetrics);
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    JSONObject clientData = new JSONObject();
    try {/*from ww  w  .jav  a 2s . c  o m*/
        clientData.put("os_version", CommonUtil.getOsVersion(context));
        clientData.put("platform", "android");
        clientData.put("language", Locale.getDefault().getLanguage());
        clientData.put("deviceid", tm.getDeviceId() == null ? "" : tm.getDeviceId());//
        clientData.put("appkey", CommonUtil.getAppKey(context));
        clientData.put("resolution", displaysMetrics.widthPixels + "x" + displaysMetrics.heightPixels);
        clientData.put("ismobiledevice", true);
        clientData.put("phonetype", tm.getPhoneType());//
        clientData.put("imsi", tm.getSubscriberId());
        clientData.put("network", CommonUtil.getNetworkTypeWIFI2G3G(context));
        clientData.put("time", CommonUtil.getTime());
        clientData.put("version", CommonUtil.getVersion(context));
        clientData.put(UserIdentifier, CommonUtil.getUserIdentifier(context));

        SCell sCell = CommonUtil.getCellInfo(context);

        clientData.put("mccmnc", sCell != null ? "" + sCell.MCCMNC : "");
        clientData.put("cellid", sCell != null ? sCell.CID + "" : "");
        clientData.put("lac", sCell != null ? sCell.LAC + "" : "");
        clientData.put("modulename", Build.PRODUCT);
        clientData.put("devicename", CommonUtil.getDeviceName());
        clientData.put("wifimac", wifiManager.getConnectionInfo().getMacAddress());
        clientData.put("havebt", adapter == null ? false : true);
        clientData.put("havewifi", CommonUtil.isWiFiActive(context));
        clientData.put("havegps", locationManager == null ? false : true);
        clientData.put("havegravity", CommonUtil.isHaveGravity(context));//

        LatitudeAndLongitude coordinates = CommonUtil.getLatitudeAndLongitude(context,
                UmsAgent.mUseLocationService);
        clientData.put("latitude", coordinates.latitude);
        clientData.put("longitude", coordinates.longitude);
        CommonUtil.printLog("clientData---------->", clientData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return clientData;
}