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.dealsmessanger.android.DemoActivity.java

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

    setContentView(R.layout.main);//from  w  w w  . jav a2  s. c om
    mDisplay = (TextView) findViewById(R.id.display);

    context = getApplicationContext();

    // Check device for Play Services APK. If check succeeds, proceed with GCM registration.
    //        if (checkPlayServices()) {
    //            gcm = GoogleCloudMessaging.getInstance(this);
    //            regid = getRegistrationId(context);
    //
    //            if (regid.isEmpty()) {
    //                registerInBackground();
    //            }
    //        } else {
    //            Log.i(TAG, "No valid Google Play Services APK found.");
    //        }
    registerInBackground();
    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the location provider
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default

    criteria.setCostAllowed(false);
    // get the best provider depending on the criteria
    provider = locationManager.getBestProvider(criteria, false);

    // the last known location of this provider
    location = locationManager.getLastKnownLocation(provider);

    mylistener = new MyLocationListener();

    if (location != null) {
        mylistener.onLocationChanged(location);
    } else {
        // leads to the settings because there is no last known location
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }
    // location updates: at least 1 meter and 200millsecs change
    locationManager.requestLocationUpdates(provider, 200, 1, mylistener);

}

From source file:com.collectme.cordova.calgeolocation.CalGeolocation.java

private boolean isLocationProviderEnabled(String provider) {
    LocationManager locationManager = (LocationManager) this.cordova.getActivity()
            .getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(provider);
}

From source file:com.quantcast.measurement.service.QCLocation.java

void setupLocManager(Context appContext) {
    if (appContext == null)
        return;//from  ww w .  ja v  a  2s  .  c  o m

    _locManager = (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE);
    if (_locManager != null) {
        //specifically set our Criteria. All we need is a general location
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        criteria.setSpeedRequired(false);

        _myProvider = _locManager.getBestProvider(criteria, true);

        _geocoder = new Geocoder(appContext);
    }
    QCLog.i(TAG, "Setting location provider " + _myProvider);
}

From source file:com.careme.apvereda.careme.AccumulatorService.java

@Override
public int onStartCommand(Intent intenc, int flags, int idArranque) {
    SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("basicData",
            Context.MODE_PRIVATE);
    String email = sharedPref.getString("email", "");

    //Uncomment to use Nimbees features

    /*if (email.compareTo("") != 0) {
    try {/*www . j a va2s.c  o  m*/
        // Initialize library calling the init method on the Nimbees Client
        NimbeesClient.init(this);
    } catch (NimbeesException e) {
        e.printStackTrace();
    }
    NimbeesClient.getUserManager().register("email", new NimbeesRegistrationCallback() {
        @Override
        public void onSuccess() {
            /* Registration was successful!
            Toast.makeText(getApplicationContext(),
                    "xito en el registro", Toast.LENGTH_LONG).show();
        }
            
        @Override
        public void onFailure(NimbeesException failure) {
            /* Registration failed
            Toast.makeText(getApplicationContext(),
                    "Fallo en el registro", Toast.LENGTH_LONG).show();
        }
    });
    }
    */
    //Toast.makeText(this,"Servicio arrancado "+ idArranque, Toast.LENGTH_SHORT).show();

    // Obtain a reference to the Location Manager
    locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();
    crit.setAccuracy(Criteria.ACCURACY_FINE);
    crit.setPowerRequirement(Criteria.POWER_LOW);
    provider = locManager.getBestProvider(crit, true);

    // And register to obtain current location updates
    locListener = new LocationListener() {
        public void onLocationChanged(Location loc) {
            // Insert a new entry on History
            History history = new History(loc.getLatitude(), loc.getLongitude(), new Date());
            db.insertHistory(history);
            //Uncomment to use Nimbees features
            /*
            try {
            sendPersonalizado(loc);
            } catch (Exception e) {
            }*/
            /*
            Monitor makes the monitoring of the user to determine if he/she has lost
            */
            monitor(loc);
        }

        @Override
        public void onStatusChanged(String provider, int stat, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    // We want to update the current location every time the user moves MIN_DISTANCE
    locManager.requestLocationUpdates(provider, 0, MIN_DISTANCE, locListener);
    return START_STICKY;
}

From source file:com.gsma.rcs.ri.messaging.geoloc.EditGeoloc.java

/**
 * Set the location of the device/*  ww  w.j  av a2 s . c  o  m*/
 */
protected void setMyLocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = lm.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Location lastKnownLoc = lm.getLastKnownLocation(bestProvider);
    if (lastKnownLoc != null) {
        mLatitudeEdit.setText(String.valueOf(lastKnownLoc.getLatitude()));
        mLongitudeEdit.setText(String.valueOf(lastKnownLoc.getLongitude()));
        mAccuracyEdit.setText(String.valueOf(lastKnownLoc.getAccuracy()));
    }
    super.onResume();
}

From source file:com.guardtrax.ui.screens.SplashScreen.java

private void initialize() {
    if (locationManagerObj == null) {
        locationManagerObj = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        try {/*from  ww w . java2 s  . c  o  m*/
            gps_enabled = locationManagerObj.isProviderEnabled(LocationManager.GPS_PROVIDER);

            //network_enabled = locationManagerObj.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }
    }

    // don't start listeners if no provider is enabled - Changed to to look for both
    //if (!gps_enabled) 
    if (!gps_enabled && !network_enabled) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(SplashScreen.this);
        dialog.setTitle("Info");
        dialog.setMessage("Please enable GPS!");
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.exit(0);
            }
        });
        dialog.show();
    } else {
        Runnable showWaitDialog = new Runnable() {
            @Override
            public void run() {
                Looper.prepare();

                int i = 0;

                //if syncComplete is true already it means that we are not trying to sync, hence delay so that splash screen can close slowly
                if (syncComplete) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
                } else {
                    while (!syncComplete || i++ < 10) {
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {
                            break;
                        }
                    }

                    //make sure background task is completed.  If not, force it closed
                    if (!syncComplete) {
                        try {
                            if (syncdb.getStatus() != AsyncTask.Status.FINISHED)
                                syncdb.cancel(true);
                        } catch (Exception e) {
                        }
                    }
                }

                //After receiving first GPS Fix dismiss the Progress Dialog
                dialog.dismiss();

                //calling the tab class causes the current tab to be displayed (set to tab(0) which is the HomeScreen)

                Intent intent = new Intent();
                intent.setClass(SplashScreen.this, HomeScreen.class);
                startActivity(intent);

                //transition from splash to main menu is slowed down to a fade by this command
                overridePendingTransition(R.anim.activityfadein, R.anim.splashfadeout);

                SplashScreen.this.finish();
            }
        };

        // Create a Dialog to let the User know that we're waiting for a GPS Fix
        dialog = ProgressDialog.show(SplashScreen.this, "Please wait", "Initializing ...", true);

        Thread t = new Thread(showWaitDialog);
        t.start();
    }
}

From source file:com.example.testapplication.DialogLocation.java

@SuppressLint("InlinedApi")
@Override/*from   w  w  w . j  a  va  2 s .c om*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mProgressBar = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv.setVisibility(ProgressBar.GONE);

    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    mCriteria = new Criteria();
    int criteria = (mGpsPref) ? Criteria.POWER_HIGH : Criteria.POWER_MEDIUM;
    mCriteria.setPowerRequirement(criteria);

    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    int telephonyInfo = tm.getNetworkType();

    boolean networkAvailable = true;

    if ((telephonyInfo == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected())
            || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    int locationMode = -1;
    int locationType = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                    Settings.Secure.LOCATION_MODE);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }

        if (locationMode == Settings.Secure.LOCATION_MODE_OFF
                || (!networkAvailable && (mProvider.matches("network"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mGpsPref && (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY || !networkAvailable)
                    ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network") && (locationMode == Settings.Secure.LOCATION_MODE_BATTERY_SAVING
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = USING_NETWORK_LOCATION;

    } else {
        if (mProvider.matches("passive") || !networkAvailable
                && (mProvider.matches("network") || (!mGpsPref && mProvider.matches("gps"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mProvider.matches("gps") && mGpsPref)
            locationType = ((mProvider.matches("gps")) || !networkAvailable) ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network"))
            locationType = USING_NETWORK_LOCATION;
    }

    switch (locationType) {
    case NO_LOCATION_SERVICES:
        builder.setTitle(DIALOG_LOCATION_NO_LOCATION_SERVICES_TITLE);
        builder.setMessage(DIALOG_LOCATION_NO_LOCATION_SERVICES_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        mAbortRequest = true;
        break;
    case USING_ONLY_GPS_LOCATION:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setMessage(DIALOG_LOCATION_ONLY_GPS_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        builder.setView(mProgressBar);
        break;
    case USING_GPS_LOCATION_NETWORK_AVAILABLE:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setPositiveButton(DIALOG_LOCATION_USE_NETWORK, null);
        builder.setView(mProgressBar);
        break;
    case USING_NETWORK_LOCATION:
        builder.setView(mProgressBar);
        builder.setTitle(DIALOG_LOCATION_UPDATING_NETWORK_TITLE);
        break;
    }

    builder.setNegativeButton(DIALOG_LOCATION_CANCEL, cancelListener);
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mFragmentId);
                mLocationManager.removeUpdates(DialogLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }
            return false;
        }
    });

    mRealDialog = builder.create();
    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    return mRealDialog;
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.Home.CarBrowse.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.activity_car_browse, container, false);

    final SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(new Criteria(), false);

    return view;/*  w w w.j  a va2s . co  m*/
}

From source file:com.nextgis.firereporter.SendReportActivity.java

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

    setContentView(R.layout.report);//  w w w. ja v  a2 s. c o  m

    //add fragment
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    frCompass = (CompassFragment) getSupportFragmentManager().findFragmentByTag("COMPASS");
    if (frCompass == null) {
        frCompass = new CompassFragment();
        fragmentTransaction.add(R.id.compass_fragment_container, frCompass, "COMPASS").commit();
    }

    getSupportFragmentManager().executePendingTransactions();

    getSupportActionBar().setHomeButtonEnabled(true);

    edLatitude = (EditText) findViewById(R.id.edLatitude);
    edLongitude = (EditText) findViewById(R.id.edLongitude);
    edAzimuth = (EditText) findViewById(R.id.edAzimuth);
    edDistance = (EditText) findViewById(R.id.edDistance);
    edComment = (EditText) findViewById(R.id.edComment);

    edDistance.setText("100");

    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (mLocationManager != null) {

        for (String aProvider : mLocationManager.getProviders(false)) {
            if (aProvider.equals(LocationManager.GPS_PROVIDER)) {
                gpsAvailable = true;
            }
        }

        if (gpsAvailable) {
            Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            if (location != null) {
                float lat = (float) (location.getLatitude());
                float lon = (float) (location.getLongitude());
                edLatitude.setText(Float.toString(lat));
                edLongitude.setText(Float.toString(lon));
            } else {
                edLatitude.setText(getString(R.string.noLocation));
                edLongitude.setText(getString(R.string.noLocation));
            }

            mLocationListener = new LocationListener() {
                public void onStatusChanged(String provider, int status, Bundle extras) {
                    switch (status) {
                    case LocationProvider.OUT_OF_SERVICE:
                        break;
                    case LocationProvider.TEMPORARILY_UNAVAILABLE:
                        break;
                    case LocationProvider.AVAILABLE:
                        break;
                    }
                }

                public void onProviderEnabled(String provider) {
                }

                public void onProviderDisabled(String provider) {
                }

                public void onLocationChanged(Location location) {
                    float lat = (float) (location.getLatitude());
                    float lon = (float) (location.getLongitude());
                    edLatitude.setText(Float.toString(lat));
                    edLongitude.setText(Float.toString(lon));

                    // FIXME: also need to calculate declination?
                }
            }; // location listener
        } else {
            edLatitude.setText(getString(R.string.noGPS));
            edLongitude.setText(getString(R.string.noGPS));
            edLatitude.setEnabled(false);
            edLongitude.setEnabled(false);
        }
    }

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    boolean accelerometerAvailable = false;
    boolean magnetometerAvailable = false;
    for (Sensor aSensor : mSensorManager.getSensorList(Sensor.TYPE_ALL)) {
        if (aSensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            accelerometerAvailable = true;
        } else if (aSensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            magnetometerAvailable = true;
        }
    }

    compassAvailable = accelerometerAvailable && magnetometerAvailable;
    if (compassAvailable) {
        //frCompass = (CompassFragment) getSupportFragmentManager().findFragmentByTag("COMPASS");
        if (frCompass != null) {
            frCompass.SetAzimuthCtrl(edAzimuth);
        }
    } else {
        edAzimuth.setText(getString(R.string.noCompass));
        edAzimuth.setEnabled(false);
    }
}

From source file:info.snowhow.plugin.RecorderService.java

@Override
public void onCreate() {
    Log.d(LOG_TAG, "onCreate called in service");
    mgpsll = new MyLocationListener();
    mnetll = new MyLocationListener();
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    editor = sharedPref.edit();/*from   w w  w .  j  av a2  s.c om*/
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Log.d(LOG_TAG, "locationManager initialized, starting intent");

    try {
        PackageManager packageManager = this.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageInfo(this.getPackageName(), 0);
        applicationName = packageManager.getApplicationLabel(packageInfo.applicationInfo).toString();
    } catch (android.content.pm.PackageManager.NameNotFoundException e) {
        /* do nothing, fallback is used as name */
    }

    registerReceiver(RecorderServiceBroadcastReceiver, new IntentFilter(ifString));
    startGPSS();
}