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.iverson.toby.rhealth.MainActivity.java

public void openMenu() {

    setContentView(R.layout.open);//from  w w  w.  ja  va 2  s  .  c o  m

    final EditText restSearch = (EditText) findViewById(R.id.editsearch);
    Button sbtn = (Button) findViewById(R.id.search_button);
    Button lbtn = (Button) findViewById(R.id.location_button);

    // search button
    sbtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String psearch = restSearch.getText().toString();

            setContentView(R.layout.httptestlist);

            //getting rid of special characters
            psearch = psearch.toUpperCase();
            psearch = psearch.replaceAll(" ", "%20");
            psearch = psearch.replaceAll("&", "%26");
            psearch = psearch.replaceAll("!", "%21");
            if (psearch.contains("'")) {
                psearch = psearch.substring(0, psearch.indexOf("'"));
            }

            //creating query
            queryGoogle = new StringBuilder();
            queryGoogle.append("https://maps.googleapis.com/maps/api/place/textsearch/xml?");
            queryGoogle.append("location=44.9756997,-93.2664641&");
            queryGoogle.append("radius=10000&");
            queryGoogle.append("types=" + type + "&");
            queryGoogle.append("query=" + psearch + "&");
            queryGoogle.append("key=" + APIKEY);

            new SearchGooglePlaces().execute(queryGoogle.toString());

        }
    });
    //location button
    lbtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            setContentView(R.layout.httptestlist);

            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            LocationListener myLocationListener = new MyLocationListener();

            locationResult = new MyLocation.LocationResult() {
                @Override
                public void gotLocation(Location location) {
                    latitude = String.valueOf(location.getLatitude());
                    longitude = String.valueOf(location.getLongitude());
                    progressDialog.dismiss();
                    new GetCurrentLocation().execute(latitude, longitude);
                }
            };

            /*****Enter lat lon for testing*****/
            //latitude = String.valueOf(44.9157615);
            //longitude = String.valueOf(-93.2629201);

            MyRunnable myRun = new MyRunnable();
            myRun.run();

            progressDialog = ProgressDialog.show(MainActivity.this, "Finding your location", "Please wait...",
                    true);
            queryGoogle = new StringBuilder();
            queryGoogle.append("https://maps.googleapis.com/maps/api/place/nearbysearch/xml?");
            queryGoogle.append("location=" + latitude + "," + longitude + "&");
            queryGoogle.append("radius=" + radius + "&");
            queryGoogle.append("types=" + type + "&");
            queryGoogle.append("sensor=true&"); //Must be true if queried from a device with GPS
            queryGoogle.append("key=" + APIKEY);
            new QueryGooglePlaces().execute(queryGoogle.toString());

        }
    });

}

From source file:com.projectattitude.projectattitude.Activities.MapActivity.java

/**
 * Handles everything//  ww w  . ja v a 2 s .  c  o  m
 * @param map
 */
@Override
public void onMapReady(GoogleMap map) {
    mMap = map;

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    if (ContextCompat.checkSelfPermission(MapActivity.this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(MapActivity.this,
                new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION },
                MY_PERMISSION_ACCESS_COARSE_LOCATION);
    }

    /**
     * http://stackoverflow.com/questions/18425141/android-google-maps-api-v2-zoom-to-current-location 4/1/2017 4:20pm
     */
    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null) {
        map.animateCamera(CameraUpdateFactory
                .newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
                .zoom(15) // Sets the zoom
                .bearing(0) // Sets the orientation of the camera to east
                .tilt(40) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    enableMyLocation();

    //couldn't get ColorMap to work, so made one for the meantime
    HashMap<String, BitmapDescriptor> hm = new HashMap<String, BitmapDescriptor>();
    hm.put("Anger", BitmapDescriptorFactory.fromResource(R.drawable.ic_anger_colour_36px));//defaultMarker(356));
    hm.put("Confusion", BitmapDescriptorFactory.fromResource(R.drawable.ic_confusion_colour_36px));//defaultMarker(19));
    hm.put("Disgust", BitmapDescriptorFactory.fromResource(R.drawable.ic_disgust_colour_36px));//defaultMarker(65));
    hm.put("Fear", BitmapDescriptorFactory.fromResource(R.drawable.ic_fear_colour_36px));//defaultMarker(42));
    hm.put("Happiness", BitmapDescriptorFactory.fromResource(R.drawable.ic_happiness_colour_36px));//defaultMarker(160));
    hm.put("Sadness", BitmapDescriptorFactory.fromResource(R.drawable.ic_sadness_colour_36px));//defaultMarker(60));
    hm.put("Shame", BitmapDescriptorFactory.fromResource(R.drawable.ic_shame_colour_36px));//defaultMarker(200));
    hm.put("Surprise", BitmapDescriptorFactory.fromResource(R.drawable.ic_surprise_colour_36px));//defaultMarker(22));

    //Taken from https://developers.google.com/maps/documentation/android-api/marker
    //On March 21st at 17:53

    map.setOnInfoWindowClickListener(this);

    if (getIntent().hasExtra("users")) {
        ArrayList<User> users = (ArrayList<User>) getIntent().getSerializableExtra("users");
        GPSTracker gps = new GPSTracker(MapActivity.this);
        //LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        //LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            latitude = Math.round(gps.getLatitude() * 10000d) / 10000d;
            longitude = Math.round(gps.getLongitude() * 10000d) / 10000d;

            if (latitude != 0 & longitude != 0) {
                Toast.makeText(MapActivity.this, "Found your location", Toast.LENGTH_LONG).show();

                Log.d("Distance", "Current Location: " + latitude + " " + longitude);
                for (int i = 0; i < users.size(); i++) {

                    Mood mood = users.get(i).getFirstMood();

                    //                if(mood.getLatitude()!= null && mood.getLongitude() != null) {
                    if (mood != null) {
                        Double returned = calculateDistance(latitude, longitude, mood.getLatitude(),
                                mood.getLongitude());
                        returned = returned / 1000;

                        Log.d("Distance", "Current Distance: " + returned);
                        Log.d("Distance", "Current comparison to: " + users.get(i).getUserName() + " "
                                + mood.getEmotionState());

                        if (returned < 5) {
                            map.addMarker(new MarkerOptions()
                                    .position(new LatLng(mood.getLatitude(), mood.getLongitude()))
                                    .title(mood.getMaker()).snippet(mood.getEmotionState())
                                    .icon(hm.get(mood.getEmotionState()))).setTag(mood);
                        }
                    }
                }
            }

            else {
                Toast.makeText(MapActivity.this, "Could not find your location, please try again!",
                        Toast.LENGTH_LONG).show();
            }
        } else {

            Toast.makeText(MapActivity.this, "Please turn on GPS for locations!", Toast.LENGTH_LONG).show();
        }
    }

    else if (getIntent().hasExtra("user")) {
        ArrayList<Mood> userMoodList = (ArrayList<Mood>) getIntent().getSerializableExtra("user");
        for (int i = 0; i < userMoodList.size(); i++) { //TODO this will get EVERY mood from the user, which could be too many

            Mood mood = userMoodList.get(i);

            if (mood.getLongitude() == 0 && mood.getLatitude() == 0) {
                Log.d("MapMoods", "Mood: " + mood.getEmotionState() + "not mapped");
            } else {

                map.addMarker(new MarkerOptions().position(new LatLng(mood.getLatitude(), mood.getLongitude()))
                        .title(mood.getMaker()).snippet(mood.getEmotionState())
                        .icon(hm.get(mood.getEmotionState()))).setTag(mood);

            }
        }
    }

    else {
        Toast.makeText(MapActivity.this, "MIts Fucked, nothing go passed", Toast.LENGTH_LONG).show();
    }
}

From source file:dtu.ds.warnme.app.location.FollowMeLocationSource.java

private void init() {
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    criteria.setAltitudeRequired(true);/*from w ww  .  j  a  v  a2  s  .co m*/
    criteria.setBearingRequired(true);
    criteria.setSpeedRequired(true);
    criteria.setCostAllowed(true);
}

From source file:com.sorin.cloudcog.xivelypull.LocationActivity.java

/**
 * This sample demonstrates how to incorporate location based services in
 * your app and process location updates. The app also shows how to convert
 * lat/long coordinates to human-readable addresses.
 *//*  w  w w  . j  a  v  a  2s.  c om*/
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_coordinates);

    // Restore apps state (if exists) after rotation.
    if (savedInstanceState != null) {
        mUseFine = savedInstanceState.getBoolean(KEY_FINE);
        mUseBoth = savedInstanceState.getBoolean(KEY_BOTH);
    } else {
        mUseFine = false;
        mUseBoth = false;
    }
    mLatLng = (TextView) findViewById(R.id.latlng);
    mAddress = (TextView) findViewById(R.id.address);
    // Receive location updates from the fine location provider (gps) only.
    mFineProviderButton = (Button) findViewById(R.id.provider_fine);
    // Receive location updates from both the fine (gps) and coarse
    // (network) location
    // providers.
    mBothProviderButton = (Button) findViewById(R.id.provider_both);

    // The isPresent() helper method is only available on Gingerbread or
    // above.
    mGeocoderAvailable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

    // Handler for updating text fields on the UI like the lat/long and
    // address.
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case UPDATE_ADDRESS:
                mAddress.setText((String) msg.obj);
                break;
            case UPDATE_LATLNG:
                mLatLng.setText((String) msg.obj);
                break;
            }
        }
    };
    // Get a reference to the LocationManager object.
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}

From source file:com.rizal.lovins.smartkasir.activity.SettingsActivity.java

private void location() {
    LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;//from  ww w.j a v  a2  s . co  m
    }
    Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location != null) {
        new AlertDialog.Builder(SettingsActivity.this).setTitle("Location")
                .setMessage("lat: " + location.getLatitude() + ", long: " + location.getLongitude())
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }
}

From source file:com.kinvey.samples.citywatch.CityWatch.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Logger.getLogger(HttpTransport.class.getName()).setLevel(LOGGING_LEVEL);

    kinveyClient = ((CityWatchApplication) getApplication()).getClient();

    if (!kinveyClient.user().isUserLoggedIn()) {
        login();//  w  w w .  j a v a  2s .  co  m
    } else {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Note there is no call to SetContentView(...) here.
        // Check out onTabSelected()-- the selected tab and associated
        // fragment
        // is
        // given
        // android.R.id.content as it's parent view, which *is* the content
        // view. Basically, this approach gives the fragments under the tabs
        // the
        // complete window available to our activity without any unnecessary
        // layout inflation.
        setUpTabs();

        curEntity = new CityWatchEntity();
        nearbyAddress = new ArrayList<Address>();
        nearbyEntities = new ArrayList<CityWatchEntity>();

        locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 100, this);

        if (Geocoder.isPresent()) {
            geocoder = new Geocoder(this);
        }

        // get last known location for a quick, rough start. Try GPS, if
        // that
        // fails, try network. If that fails wait for fresh data
        lastKnown = locationmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnown == null) {
            lastKnown = locationmanager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (lastKnown == null) {
            // if the device has never known it's location, start at 0...?
            lastKnown = new Location(TAG);
            lastKnown.setLatitude(0.0);
            lastKnown.setLongitude(0.0);
        }
        Log.i(TAG, "lastKnown -> " + lastKnown.getLatitude() + ", " + lastKnown.getLongitude());
        setLocationInEntity(lastKnown);
    }

}

From source file:com.adampmarshall.speedo.LocationActivity.java

@Override
protected void onStart() {
    super.onStart();

    // Check if the GPS setting is currently enabled on the device.
    // This verification should be done during onStart() because the system
    // calls this method
    // when the user returns to the activity, which ensures the desired
    // location provider is
    // enabled each time the activity resumes from the stopped state.
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!gpsEnabled) {
        // Build an alert dialog here that requests that the user enable
        // the location services, then when the user clicks the "OK" button,
        // call enableLocationSettings()
        new EnableGpsDialogFragment().show(getSupportFragmentManager(), "enableGpsDialog");
    }/*w w  w . j  a v  a 2s.c o m*/
}

From source file:com.googlecode.sl4a.facade.LocationFacade.java

public LocationFacade(AndroidLibraryManager manager) {
    mContext = manager.getContext();//from w w  w.  j  a v a  2  s. c om
    mEventFacade = manager.getReceiver(AndroidEvent.class);
    mManager = manager;
    mGeocoder = new Geocoder(mContext);
    mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    mLocationUpdates = new HashMap<>();
}

From source file:ly.apps.android.rest.client.example.activities.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textViewDescription = (TextView) findViewById(R.id.textview_description);
    textViewTemp = (TextView) findViewById(R.id.textview_temp);
    imageViewIcon = (ImageView) findViewById(R.id.imageview_icon);
    textViewWind = (TextView) findViewById(R.id.textview_wind_response);
    textViewHumidity = (TextView) findViewById(R.id.textview_humidity_response);
    textViewTempMax = (TextView) findViewById(R.id.textview_tempmax_response);
    textViewTempMin = (TextView) findViewById(R.id.textview_tempmin_response);
    textViewCity = (TextView) findViewById(R.id.textview_city);
    contentProgressBar = (LinearLayout) findViewById(R.id.content_progressbar);
    linearLayoutContent = (LinearLayout) findViewById(R.id.content);
    contentBottom = (LinearLayout) findViewById(R.id.bottom_content);
    descriptionTempContent = (LinearLayout) findViewById(R.id.description_temp_content);

    RestClient client = RestClientFactory.defaultClient(getApplicationContext());
    api = RestServiceFactory.getService(getString(R.string.base_url), OpenWeatherAPI.class, client);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    checkImmersiveMode();/*from  w  w  w  .  j av  a 2  s  .c  o m*/

    if ((location != null) && checkConnection(getApplicationContext())) {
        setLocation(location);
    } else {
        failMessage();
    }

}

From source file:com.mobilevangelist.glass.helloworld.GetTheWeatherActivity.java

public static Location getLastLocation(Context context) {
    Location result = null;/*  ww  w . ja  v a2 s.c om*/
    LocationManager locationManager;
    Criteria locationCriteria;
    List<String> providers;

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    locationCriteria = new Criteria();
    locationCriteria.setAccuracy(Criteria.NO_REQUIREMENT);
    providers = locationManager.getProviders(locationCriteria, true);

    // Note that providers = locatoinManager.getAllProviders(); is not used because the
    // list might contain disabled providers or providers that are not allowed to be called.

    //Note that getAccuracy can return 0, indicating that there is no known accuracy.

    for (String provider : providers) {
        Location location = locationManager.getLastKnownLocation(provider);
        if (result == null) {
            result = location;
        } else if (result.getAccuracy() == 0.0) {
            if (location.getAccuracy() != 0.0) {
                result = location;
                break;
            } else {
                if (result.getAccuracy() > location.getAccuracy()) {
                    result = location;
                }
            }
        }
    }

    return result;
}